从控制器下载时,Symfony正在添加文件大小

时间:2017-10-16 23:31:44

标签: symfony vichuploaderbundle

我已经使用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

2 个答案:

答案 0 :(得分:2)

您可以使用BinaryFileResponsedoc )喜欢:

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

return $response;

答案 1 :(得分:2)

编辑:HTTP响应似乎是正确的。

既然你正在使用VichUploaderBundle,为什么不直接使用它的助手呢?

<img src="{{ vich_uploader_asset(license, 'frontName') }}" alt="{{ license.frontName }}">