HTTP图像输出提供blob数据而不是图像

HTTP图像输出提供blob数据而不是图像

问题描述:

My url looks like ..../image/view?id=6

Navigating to this url should give an image from my database. But currently I'm getting a bunch of weird characters as a response.

When I output (see below) I'm seeing my image.

<img src="data:image/jpeg;base64,'.base64_encode( $image->Data ).'"/>

I'm using this piece of code to generate my HTTP response, but the response is just the blob data:

 header('Content-Type :'.$image->Extension);
 header('Content-Disposition: filename='.$image->Name.'.'.$image->Extension);
 header('Content-Length: ' . strlen($image->Data));
 $response->format = Response::FORMAT_RAW;
 $response->data = $image->Data;

Current output begins with:

����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C     $.' ",#(7),01444'9=82<.342��C     2!!22222222222222222222222222222222222222222222222222���"��    ���}!1AQa"q2���#B��R��$3br� 

Headers used:

   Accept-Ranges: bytes
   Cache-Control: private
   Content-Disposition: inline;        filename="FYdsl67l4PWJQ7QFFeo14Ena76gr0pEP.jpg"
   Content-Length: 320135
   Content-Type: image/jpeg
   Date: Mon, 28 Jan 2019 19:05:11 GMT
   Expires: 0
   Pragma: public
   Server: Microsoft-IIS/8.5
   X-Powered-By: PHP/5.6.24, ASP.NET

Any help would be appreciated

Issue has been fixed, seems that my file was in an incorrect encoding ... File needed to be iso instead of utf-8

If your image is base64 encoded when it goes in to the database, to display it, you either need to

  1. Use base64_decode($img) and then display it. OR
  2. Do this: echo '<img src="data:image/jpeg;base64,' . $image->Data . '"/>;

What you seem to be doing is encoding it again.

You should probably use Response::sendContentAsFile() to send this file:

return Yii::$app->response->sendContentAsFile(
    $image->Data, 
    $image->Name . '.' . $image->Extension, 
    ['mimeType' => FileHelper::getMimeTypeByExtension($image->Name . '.' . $image->Extension)]
);

Note that Conent-Type header is not the same as file extension - refer to FileHelper::getMimeTypeByExtension().