0

我已经使用 VichUploaderBundle 上传了一张图片,正在返回一个图片文件,如下所示:

/**
 * Show license image.
 *
 * @param Request $request
 * @return Response
 */
public function showImageAction(Request $request,$id)
{
    $em = $this->getDoctrine()->getManager();
    $license = $em->getRepository('MyCarBundle:License')->findOneById($id);

    $fileName = $license->getFrontName();
    $user = $this->getUser();
    $contents = '';
    $filePath = __DIR__ . '/../../../../app/uploads/licenses/'. $user->getId().'/'.$fileName;


    $response = new Response();
    $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $fileName);
    $response->headers->set('Content-Disposition', $disposition);
    $response->headers->set('Content-Type', 'image/jpg');
    $response->setContent(file_get_contents($filePath));

    return $response;
}

并在 html 中尝试显示图像,就像这样

<img class="img-fluid w-100 u-block-hover__main--zoom-v1" src="{{ path('license_show_image',{'id':license.id}) }}" alt="Image Description">

图片上传成功。当我在上传的文件夹中打开图像时,它显示正常。

但是图像没有显示在浏览器中。直接访问网址时,图像正在下载但无法打开。它给了我以下错误:

The file “ODL_Eng_Full_Back-5.jpg” could not be opened.

有谁知道发生了什么事?

更新:

Symfony 在下载时增加了大约 700kb 的文件大小。上传后它似乎有适当的文件大小,但下载会增加文件大小。这里发生了什么?

更新 2:

这些是标题:

Request URL:http://localhost/app-temp/web/app_dev.php/account/license/2/show-image
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Disposition:inline; filename="ODL_Eng_Full_Back.jpg"
Content-Type:image/jpg
Date:Tue, 17 Oct 2017 23:31:02 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.27 (Unix) PHP/7.1.8
Transfer-Encoding:chunked
X-Debug-Token:0e53c1
X-Debug-Token-Link:http://localhost/app-temp/web/app_dev.php/_profiler/0e53c1
X-Powered-By:PHP/7.1.8
Request Headers
view source
Accept:image/webp,image/apng,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Cookie:__atuvc=54%7C42; _ga=GA1.1.1906437920.1508087850; _gid=GA1.1.1258608977.1508087850; PHPSESSID=iuhk0pr0oqtaje5371fp7q7vfk
Host:localhost
Referer:http://localhost/app-temp/web/app_dev.php/account/creditcards/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
4

2 回答 2

2

您可以使用BinaryFileResponsedoc ),例如:

$response = new BinaryFileResponse($filepath);
$response->headers->set('Content-disposition', sprintf('filename=%s', basename($filepath)));

return $response;
于 2017-10-17T09:02:37.310 回答
2

EDIT : HTTP Response seems to be correct.

Since you're using VichUploaderBundle, why not just use its helpers ?

<img src="{{ vich_uploader_asset(license, 'frontName') }}" alt="{{ license.frontName }}">
于 2017-10-17T09:11:18.287 回答