【问题标题】:PHP file download not recognizing file type in Chrome and EdgePHP 文件下载无法识别 Chrome 和 Edge 中的文件类型
【发布时间】:2021-04-19 00:38:26
【问题描述】:

我正在尝试创建一个简单的下载页面,该页面目前可以在 Firefox 中运行,但不能完全在 Chrome 和 Edge 中运行。要下载的文件是 mp3,位于服务器的私有目录中。

当我在 Firefox 中下载文件时,它按预期工作。如果我使用 Chrome 或 Edge 下载它,文件仍会下载,但它无法识别 文件类型,只是将其保存为无扩展名文件。
如果我将 .mp3 扩展名手动添加到下载的文件中,那很好,我可以播放曲目。

(从 index.php 向 download.php 发送 POST 请求)
-----------------
在 download.php 中,我设置了以下 HTTP 标头 并读取了文件:

header("Cache-Control: private"); 
header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"$title\"");
header("Content-Length: ".filesize($location)); 

//Force download
readfile($location);
exit();

将 'Content-type' 更改为 'audio/mpeg' 也不起作用。

我读到的大多数关于使用 PHP 强制下载文件的文章都相互矛盾(尤其是关于 HTTP 标头),我找不到专门针对我的情况的答案。

如果问题不在于标题,我也可以提供完整代码?谢谢。

【问题讨论】:

    标签: php download http-headers cross-browser file-type


    【解决方案1】:

    你可以试试吗:

    header("Content-Disposition: attachment; filename=\"$title\".mp3");
    

    查看标题是否包含扩展名

    【讨论】:

    • 好吧,不知道我必须在其中包含扩展...有点困惑,因为它确实在 Firefox 中工作。 header('Content-Disposition: attachment; filename="'.$title.'.mp3"' );现在完美运行,谢谢。
    • 最好是这样做:$title = $title.".mp3";然后声明标题 Content-Disposition
    • 我把它改成了header('Content-Disposition: attachment; filename="'. $title .'.'. $ext .'"'); $ext = pathinfo($location, PATHINFO_EXTENSION); 所以现在它应该适用于所有文件类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多