php如何?檔案下載
1. 設定超連結的href屬性
如果瀏覽器不能解析該檔案,瀏覽器會自動下載。而如果檔案是圖片或者txt,會直接在瀏覽器中開啟。
2. 輸出檔案流
//download.php
//頁面載入的時候就調用
downloadFile("3.rar","something.rar");
//$filePath是伺服器的檔案地址
//$saveAsFileName是使用者指定的下載後的檔案名稱
function downloadFile($filePath,$saveAsFileName){
// 清空緩衝區並關閉輸出緩衝
ob_end_clean();
//r: 以唯讀方式開啟,b: 強制使用二進位模式
$fileHandle=fopen($filePath,"rb");
if($fileHandle===false){
echo "Can not find file: $filePath\n";
exit;
}
Header("Content-type: application/octet-stream");
Header("Content-Transfer-Encoding: binary");
Header("Accept-Ranges: bytes");
Header("Content-Length: ".filesize($filePath));
Header("Content-Disposition: attachment; filename=\"$saveAsFileName\"");
while(!feof($fileHandle)) {
//從檔案指標 handle 讀取最多 length 個位元組
echo fread($fileHandle, 32768);
}
fclose($fileHandle);
}
杭州php工程師註:
(1)download.php可以設定為標籤的href屬性,點擊標籤,則瀏覽器會提示下載。
(2)jQuery類比觸發的click事件時有bug,應該使用html對象的click方法。$('#hyperLink')[0].click();
(3)jQuery Mobile會改變的行為。所以,在使用jQuery Mobile時,無論手動點擊還是java類比點擊,都會跳轉到download.php頁面,並不會觸發下載。(4)location.href或location.replace定向到download.php也可以實現下載。這種方法不受jQuery Mobile的影響。
(5)以上兩種方法進行下載時,chrome會提示“Resource interpreted as Document but transferred with MIME type application/octet-stream”。為增加html5屬性download可以解決這個問題。而location.href或location.replace觸發的下載,暫無辦法解決。