php如何?檔案下載

來源:互聯網
上載者:User
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觸發的下載,暫無辦法解決。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.