首页 文章

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

提问于
浏览
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.

有谁知道最近发生了什么?

UPDATE:

下载时,Symfony正在为文件大小添加~700kb . 上传后似乎有适当的文件大小,但下载添加文件大小 . 这里发生了什么?

UPDATE 2:

这些是 Headers :

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 回答

  • 2

    您可以使用 BinaryFileResponsedoc),如:

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

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

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

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

相关问题