当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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 bytes 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: