开发者

How to display an image returned as a bytes in browser without prompting download?

开发者 https://www.devze.com 2023-01-29 15:20 出处:网络
I have written the following PHP function but still get the prompt to download the file: function navigateToBytes($contentType, $bytes){

I have written the following PHP function but still get the prompt to download the file:

function navigateToBytes($contentType, $bytes){
  header('Content-Type: ' .$contentType); 
  //header('Content-Transfer-Encoding: binary'); // UPDATE: as pointed out this is not needed, though it does not solve the problem
  header('Content-Length: '.strlen($bytes));
  ob_clean();
  flush();
  echo $bytes;
}

An example of calling the function:

navigateToBytes('image/jpeg', $bytes); // UPDATE: turns out this does work, using image/tiff for tiff images is when the browser does not display the image

where $bytes are the by开发者_如何学JAVAtes as read from the file.


Apologies all - turns out I was having the problem because the images I was testing were TIFF's (with the Content-Type correctly set to image/tiff) when I used a JPEG the browser would display the image!

Ultimately it is up to the browser to decide whether it can display the Content-Type you are sending.

For the record the only headers I needed to change was

Content-Type, 

I should set

Content-Length 

too unless I set

Transfer-Encoding: chunked


Try the HTTP header "Content-Disposition: Inline", however some browsers may try to save the user from seeing binary data. Here is a random blog article on that HTTP header:

http://dotanything.wordpress.com/2008/05/30/content-disposition-attachment-vs-inline/


That seems like correct behavior to me. The browser is a viewport for humans to view things in. Humans, by and large, don't want to view binary data. What do you think should happen?

Random Advice: If there's a site that's doing what you want to do, use curl to sniff the headers they're sending.

curl -I http://example.com/path/to/binary/file/that/displays/in/browser

and then use the exact same headers in your own script.


As a start, get rid of things that do not exist in HTTP (Content-Transfer-Encoding).

Then get an HTTP tracing tool, such as the Live HTTP headers plugin for Firefox, and compare "your" headers with those received for a working image.

In doubt, post the HTTP trace here.

0

精彩评论

暂无评论...
验证码 换一张
取 消