Edgar Alfonso
Edgar Alfonso

Reputation: 685

Return image from controller in symfoy2

I've looked at this question but it doesnt work for me.

my controller looks like:

 /**
 * @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;
}

But in the browser code is displayed instead of the image displayed:

browser looks like this

Thank you.

Upvotes: 0

Views: 1794

Answers (3)

Turdaliev Nursultan
Turdaliev Nursultan

Reputation: 2576

There is a special class which is designed for binary file response. I would recommend to use it instead. More info BinaryFileResponse

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

    return $response;

Upvotes: 3

Edgar Alfonso
Edgar Alfonso

Reputation: 685

Thank you @chalasr, finally it works, here's a solution:

  • first, I removed $response->headers->set('Cache-Control', 'private');
  • second, I changed the value of Content-Disposition from attachment to inline.

/**
 * @Route("/tracking")
 */
public function trackingnewsletterAction() {
    $filename =    '...\establishments\1-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;
}

Upvotes: 1

chalasr
chalasr

Reputation: 13167

You have to do :

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));
}

Upvotes: 2

Related Questions