PHP ReadFile 无法下载

php readfile does not download

提问人:RGriffiths 提问时间:9/2/2023 更新时间:9/2/2023 访问量:25

问:

我正在测试一小段代码来下载文件,但没有任何下载。我看过无数的例子(我知道这个问题已经问过很多次了),通过阅读这些例子,这应该有效。该文件肯定存在,但没有下载。

我做错了什么?

这是整个文件(称为 download.php)。

<?php

$file = $_SERVER["DOCUMENT_ROOT"] . "/uploads/test.png" ;
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

它是用一个简单的 js 函数调用的:

function download() {

    $.post("download.php", 
        function(data, status){
          ... some stuff will go in here
        }
    );
}
php 读取文件

评论

2赞 Barmar 9/2/2023
AJAX 不进行下载。文件内容位于 中。data
1赞 imvain2 9/2/2023
正如@Barmar所说,AJAX 不进行下载。一个简单的解决方案是使用类似 您的浏览器将触发下载。location.href='download.php'
0赞 RGriffiths 9/2/2023
如此简单 - 谢谢

答: 暂无答案