php下載jpg文件為空解決方法
來源:程序員人生 發布時間:2014-01-10 01:19:50 閱讀次數:3442次
jpg格式的文件,點擊在瀏覽器中打開顯示為紅叉:代碼如下:
- $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;
首先排查初始文件是否有問題:
1、echo $filepath;
2、根據輸出的文件完整路徑,打開文件,沒有問題
排除原始文件的嫌疑,然后排查在文件讀取過程中是否存在問題:
1、$filetype = "application/jpeg";
header("content-disposition: attachment; filename="{$headername}";");
將文件強制下載,下載下來發現文件大小與原始文件一致,但是打開后還是為空,可以確定在文件輸出的時候出現了問題,使用
file_put_contents("d:aaa.jpg",file_get_contents($filepath)),將文件保存到服務器,保存的文件可以打開,這時我懷疑在文件輸出到客戶端的時候編碼出了問題,經過一段時間的折騰,終于把問題解決,代碼如下:
- header("content-type: {$filetype}");
- header("expires: 0");
- header("cache-control: must-revalidate, post-check=0,pre-check=0");
- header("pragma: public");
-
- header('content-transfer-encoding: binary');
-
- ob_clean();
-
- readfile($filepath);
-
-
- exit;
此處附ob_clean()的解釋:clean (erase) the output buffer
我理解ob_clean()等于.net中的response.clear();
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈