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