从symfoy2中的控制器返回图像

时间:2016-01-22 19:12:19

标签: symfony http-headers imagesource

我看过this question,但它对我不起作用。

我的控制器看起来像:

 /**
 * @Route("/testing")
 */
public function trackingNewsletter() {
    $filename =    'T:\wamp\www\trendytouristmx\web\uploads\establishments\1-37.jpg';

    $response = new \Symfony\Component\HttpFoundation\Response();
    $response->headers->set('Cache-Control', 'private');
    $response->headers->set('Content-type', mime_content_type($filename));
    $response->headers->set('Content-Disposition', 
                            'attachment; filename="' . basename($filename) . '";');
    $response->headers->set('Content-length', filesize($filename));
    $response->sendHeaders();

    $response->setContent(file_get_contents($filename));

    return $response;
}

但是在浏览器中显示代码而不是显示的图像:

browser looks like this

谢谢。

3 个答案:

答案 0 :(得分:3)

有一个专为binary file response设计的课程。我建议改用它。更多信息BinaryFileResponse

    //$filePath = ...
    //$filename = ...
    $response = new BinaryFileResponse($filePath);
    $response->trustXSendfileTypeHeader();
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_INLINE,
        $filename,
        iconv('UTF-8', 'ASCII//TRANSLIT', $filename)
    );

    return $response;

答案 1 :(得分:1)

你必须这样做:

public function trackingNewsletter() {
    $path = 'T:\wamp\www\trendytouristmx\web\uploads\establishments\1-37.jpg';
    $response = new Symfony\Component\HttpFoundation\Response();
    $response->headers->set('Content-type', mime_content_type($path));
    $response->headers->set('Content-length', filesize($path));
    $response->sendHeaders();
    $response->setContent(readfile($path));
}

答案 2 :(得分:1)

谢谢 @chalasr ,最后它有效,这是一个解决方案:

  • 首先,我删除了points(q6_long$x, q6_long$value, pch = 5)
  • 第二,我将$response->headers->set('Cache-Control', 'private');的值从Content-Disposition更改为attachment
inline