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
觸發的下載,暫無辦法解決。