Php to download jpg files is empty solution

Source: Internet
Author: User
Tags file size php tutorial

Php Tutorial download jpg file is empty solution

In jpg format, click to open the file in the browser and display it as a Red Cross

The code is as follows:

$ Filetype = "image/pjpeg ";
Header ("content-type: {$ filetype }");
   

Header ("expires: 0 ");
Header ("cache-control: must-revalidate, post-check = 0, pre-check = 0 ");
Header ("pragma: public ");

$ File_content = file_get_contents ($ filepath );
Echo $ file_content;
Exit;

First, check whether the initial file is faulty.

1. echo $ filepath;

2. Open the file based on the complete path of the output file. No problem

Exclude suspected original files

Check whether there are problems during file reading.

1. $ filetype = "application/jpeg ";

Header ("content-disposition: attachment; filename =" {$ headername }";");

Force File Download

After downloading the file, the file size is the same as that of the original file, but it is still blank after it is opened. You can confirm that there is a problem during file output.

Use file_put_contents ("d: aaa.jpg", file_get_contents ($ filepath) to save the file to the server. The saved file can be opened.

At this time, I suspect that the encoding is wrong when the file is output to the client.

After a period of hard work, I finally solved the problem. The code is as follows:

Header ("content-type: {$ filetype }");
Header ("expires: 0 ");
Header ("cache-control: must-revalidate, post-check = 0, pre-check = 0 ");
Header ("pragma: public ");
// Add encoding settings here
Header ('content-transfer-encoding: binary ');
// The most important part here is to clear the output bytes.
Ob_clean ();
// This is equal to the two injected lines below, saving code
Readfile ($ filepath );

// $ File_content = file_get_contents ($ filepath );
// Echo $ file_content;
Exit;

Here is an explanation of ob_clean:

Clean (erase) the output buffer

I understand that ob_clean () is equal to response. clear () in. net ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.