[英]PHP force download not working?
在我的 HTML 頁面上,我向一個應該強制下載的 php 腳本發出了一個 JQuery ajax 請求,但是什么也沒發生?
在我的 html 頁面上(在鏈接的單擊事件處理程序中)...
var file = "uploads/test.css";
$.ajax(
{
type : "POST",
url : "utils/Download_File.php",
data : {"file":file}
})
Download_File.php 腳本如下所示
<?php
Download_File::download();
class Download_File
{
public static function download()
{
$file = $_POST['file'];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
readfile('http://localhost/myapp/' . $file);
exit;
}
}
?>
但由於某種原因什么都沒有發生? 我查看了 firebug 中的響應頭,但看不出任何問題。 我正在使用 Xampp。 非常感謝任何幫助。
謝謝!
您應該指定Content-Transfer-Encoding
。 此外,您應該在Content-Disposition
上指定filename
。
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile('http://localhost/myapp/'.$file);
exit;
在filename
周圍包含雙引號很重要,因為這是RFC 2231 的要求。 如果filename
不在引號中,Firefox 會在下載文件名中包含空格的文件時遇到問題。
另外,檢查以確保關閉后沒有空格?>
。 如果在關閉 PHP 標記之后存在空格,則標頭不會發送到瀏覽器。
附帶說明一下,如果您有許多要提供下載的常見文件類型,您可以考慮指定這些 MIME 類型。 這為最終用戶提供了更好的體驗。 例如,您可以執行以下操作:
//Handles the MIME type of common files
$extension = explode('.', $file);
$extension = $extension[count($extension)-1];
SWITCH($extension) {
case 'dmg':
header('Content-Type: application/octet-stream');
break;
case 'exe':
header('Content-Type: application/exe');
break;
case 'pdf':
header('Content-Type: application/pdf');
break;
case 'sit':
header('Content-Type: application/x-stuffit');
break;
case 'zip':
header('Content-Type: application/zip');
break;
default:
header('Content-Type: application/force-download');
break;
}
好的,我終於可以使用這里找到的JQuery插件來解決這個問題:
http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/ 。
現在工作正常!
使用document.location.href=URL
,而不是 ajax..
根據我的經驗,ajax 會導致問題(下載不起作用,在瀏覽器控制台上打印文件內容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.