php檔案下載中jpg檔案為空白檔案的問題

來源:互聯網
上載者:User

前一段時間粗略的學習了一點php的東西,這次公司的bugfree附件下載開啟時遇到些問題,問題癥狀如下:

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

//$file_content = file_get_contents($FilePath);
//echo $file_content;   

exit;  

此處附ob_clean()的解釋:

Clean (erase) the output buffer 

我理解ob_clean()等於.net中的Response.Clear();

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.