Return 图片来自 symfoy2 中的控制器

Return image from controller in symfoy2

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

我的控制器看起来像:

 /**
 * @Route("/testing")
 */
public function trackingNewsletter() {
    $filename =    'T:\wamp\www\trendytouristmx\web\uploads\establishments-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

谢谢。

你必须做的:

public function trackingNewsletter() {
    $path = 'T:\wamp\www\trendytouristmx\web\uploads\establishments-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));
}

谢谢@chalasr,终于成功了,这是一个解决方案:

  • 首先,我删除了$response->headers->set('Cache-Control', 'private');
  • 其次,我把Content-Disposition的值从attachment改成了inline

/**
 * @Route("/tracking")
 */
public function trackingnewsletterAction() {
    $filename =    '...\establishments-39.jpg';
    $response = new \Symfony\Component\HttpFoundation\Response();
    $response->headers->set('Content-type', mime_content_type($filename));
    $response->headers->set('Content-Disposition', 
    'inline; filename="' . basename($filename) . '";');
    $response->headers->set('Content-length', filesize($filename));
    $response->sendHeaders();

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

    return $response;
}

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

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

    return $response;