PHP强制文件下载

标签 php download

<分区>

我正在尝试使用 PHP 强制在客户端计算机上进行下载(使用文件对话框 - 没什么险恶的)。我发现许多页面建议我使用 header() 函数来控制来 self 的 PHP 脚本的响应,但我对此并不走运。我的代码如下:

$file = $_POST['fname'];

if(!($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file)) {
    die('File not found.');
} else {
    header('Pragma: public');
    header('Content-disposition: attachment; filename="tasks.zip"');
    header('Content-type: application/force-download');
    header('Content-Length: ' . filesize($file));
    header('Content-Description: File Transfer');
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    ob_end_clean();
    readfile($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file);
}

我使用这个 JavaScript 调用它:

        $.ajax({
            url: url,
            success: function(text) {
                var req = new XMLHttpRequest();
                req.open("POST", 'php/utils/getXMLfile.php', true);
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.send('fname=' + encodeURIComponent(text));
            }
        });

这会以文本形式返回文件的内容,但不会触发下载对话框。有人有什么建议吗?

最佳答案

不使用 AJAX,只需将浏览器重定向到相关的 URL。当它收到 content-disposition:attachment header 时,它将下载文件。

关于PHP强制文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11836492/

相关文章:

php - 如何检查 APC 操作码缓存是否在 PHP 中正常工作?

asp.net-mvc-4 - System.OutOfMemoryException : Exception of type 'System.OutOfMemoryException' was thrown.在mvc 4中下载大文件

ubuntu - 如何使用 wget 从网站下载所有文件(但不是 HTML)?

php - 我正在尝试在表中添加一个下拉菜单框,其中包含从 mysql 获取的数据

php - Laravel/Blade 表单添加 'required' 来选择元素

php - 为什么 PDO 构造函数不将主机、数据库名称、数据库类型等作为常规函数参数?

php - 从我的手机访问XAMPP本地主机

PHP保护PDF和DOC

c++ - 如何在使用 Windows API 下载文件时创建进度条?

javascript - 配置 Grails Controller 从服务检索数据后在浏览器中下载文件