PHP强制文件下载


PHP Force File Download

我正试图使用PHP在客户端计算机上强制下载(使用文件对话框-没有什么恶意)。我发现很多页面建议我使用header()函数来控制来自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标头时,它将下载该文件。

少数建议:

1.

if(!($baseDir . '''AgcommandPortal''agcommand''php''utils''ISOxml''' . $file)) {

相反:

if(!file_exists($baseDir ....)){

2.不需要尺寸。

3.试试这个:

 header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($fullpath));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($fullpath);
    exit;

我会尝试从PHP发送这样的头,以替换application/force-download头:

header("Content-type: application/octet-stream");

Kolink的回答对我来说很有效(将窗口位置更改为php文件),但由于我想在请求的同时发送POST变量,我最终使用了隐藏表单。我使用的代码如下:

                var url = 'php/utils/getXMLfile.php';
                var form = $('<form action="' + url + '" method="post" style="display: none;">' +
                    '<input type="text" name="fname" value="' + text + '" />' +
                    '</form>');
                $('body').append(form);
                $(form).submit();

谢谢你的回答!