php如何實現文件下載

php如何實現文件下載php

  1. 設置超連接的href屬性html

  <ahref="文件地址"></a>html5

  若是瀏覽器不能解析該文件,瀏覽器會自動下載。而若是文件是圖片或者txt,會直接在瀏覽器中打開。java

  2. 輸出文件流chrome

  //download.php瀏覽器

  //頁面加載的時候就調用服務器

  downloadFile("3.rar","something.rar");app

  //$filePath是服務器的文件地址指針

  //$saveAsFileName是用戶指定的下載後的文件名htm

  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工程師(www.proginn.com/users/hangzhou/php/)注:

  (1)download.php能夠設置爲<a>標籤的href屬性,點擊<a>標籤,則瀏覽器會提示下載。

  (2)jQuery模擬觸發<a>的click事件時有bug,應該使用html對象的click方法。$('#hyperLink')[0].click();

  (3)jQuery Mobile會改變<a>的行爲。因此,在使用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」。爲<a>增長html5屬性download能夠解決這個問題。<a href="..." download></a>而location.href或location.replace觸發的下載,暫無辦法解決。

相關文章
相關標籤/搜索