php下載jpg檔案為空白解決方案

來源:互聯網
上載者:User

php教程下載jpg檔案為空白解決方案

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.