PHP强制文件下载 [英] PHP Force File Download

查看:121
本文介绍了PHP强制文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP强制在客户端计算机上下载(文件对话框没有阴险)。我发现很多页面,建议我使用header()函数来控制我的PHP脚本的响应,但我没有运气。我的代码如下:

I am trying to use PHP to force a download on a client computer (with the file dialog- nothing sinister). I have found many pages that recommend I use the header() function to control the response from my PHP script, but I am having no luck with this. The code I have is as follows:

$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调用它:

I am calling it using this 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));
            }
        });

将文件的内容作为文本返回,但不会触发下载对话框。有人有任何建议吗?

This returns the contents of the file as text, but does not trigger a download dialog. Does anyone have any suggestions?

推荐答案

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

Instead of using AJAX, just redirect the browser to the relevant URL. When it receives the content-disposition:attachment header, it will download the file.

这篇关于PHP强制文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆