加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP强制下载无法正常工作?

发布时间:2020-12-13 13:35:42 所属栏目:PHP教程 来源:网络整理
导读:在我的 HTML页面上,我向一个强制下载的php脚本发出了一个 JQuery ajax请求,但什么都没发生? 在我的html页面上(在链接的单击事件处理程序中)… var file = "uploads/test.css";$.ajax({ type : "POST",url : "utils/Download_File.php",data : {"file":file}
在我的 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上指定文件名.
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile('http://localhost/myapp/'.$file);
exit;

重要的是在文件名周围包含双引号,因为这是RFC 2231所要求的.如果文件名不在引号中,则知道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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读