標籤:
1. 設定超連結的href屬性
<a href="檔案地址"></a>
如果瀏覽器不能解析該檔案,瀏覽器會自動下載。
而如果檔案是圖片或者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);}
註:
(1)download.php可以設定為<a>標籤的href屬性,點擊<a>標籤,則瀏覽器會提示下載。
(2)jQuery類比觸發<a>的click事件時有bug,應該使用html對象的click方法。$(‘#hyperLink‘)[0].click();
(3)jQuery Mobile會改變<a>的行為。所以,在使用jQuery Mobile時,無論手動點擊還是javascript類比點擊,都會跳轉到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”。
為<a>增加html5屬性download可以解決這個問題。<a href="..." download></a>
而location.href或location.replace觸發的下載,暫無辦法解決。
[PHP] php實現檔案下載