PHP强制下载不起作用?

PHP强制下载不起作用?,php,jquery,html,ajax,Php,Jquery,Html,Ajax,在我的HTML页面上,我向一个php脚本发出了一个jQueryAjax请求,该脚本应该强制下载,但什么都没有发生 在我的html页面上(单击事件处理程序中的链接) 下载_File.php脚本如下所示 <?php Download_File::download(); class Download_File { public static function download() { $file = $_POST['file']; heade

在我的HTML页面上,我向一个php脚本发出了一个jQueryAjax请求,该脚本应该强制下载,但什么都没有发生

在我的html页面上(单击事件处理程序中的链接)

下载_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。非常感谢您的帮助


谢谢

您应该指定
内容传输编码。此外,您还应该在
内容配置
上指定
文件名

header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile('http://localhost/myapp/'.$file);
exit;

文件名
周围加上双引号很重要,因为这是。众所周知,如果
文件名
不在引号中,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;
}

使用
document.location.href=URL
,而不是ajax


根据我的经验,ajax导致了这个问题(下载不起作用,在浏览器控制台上打印文件内容)。

这不是它的工作方式。您需要将
location.href
设置为要下载的文件,或使用iframe。检查这个问题:@Parris的可能副本你能分享一些关于这个的信息吗?我有一个下载脚本,可以做一些类似的事情(使用cURL而不是
readfile
),如果有潜在的问题,我想在我的代码中解决它。:)是的,检查这个问题:它识别问题,并试图解决它。在尝试从https下载时也会遇到一些问题,而您使用的是http…”“众所周知,如果文件名不在引号中,Firefox在下载文件名中有空格的文件时会遇到问题。”也不仅仅是Firefox。命令行wget工具(用于Linux/BSD/OSX)非常敏感,以至于您无法使用正确的文件名从VBulletin论坛软件下载。
//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;
}