【问题标题】:How to force file download upon jQuery AJAX success?如何在 jQuery AJAX 成功后强制下载文件?
【发布时间】:2013-10-17 12:21:34
【问题描述】:

我正在像这样在 php 中动态生成一个文件:

$attachment_url = "http://www.mysite.com/file.jpg";
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename( $attachment_url ).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile( $attachment_url );

然后这些数据通过jQuery.ajax

我想让它在成功时打开一个文件下载对话框。

现在我有这个:

success: function(data, textStatus, XMLHttpRequest) {
    var win = window.open();
    win.document.write(data);
}

这会打开一个新窗口并显示原始文件数据。相反,我想打开一个下载对话框。

【问题讨论】:

标签: javascript php jquery ajax download


【解决方案1】:

我不确定我是否掌握了所有必要的信息,但您可以通过 3 个文件实现目标。

下载.php

$file = $_GET['file'];
$path = '/var/www/html/';
$attachment_url = $path.$file;

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename( $attachment_url ).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile( $attachment_url );

api.php

if (isset($_GET['generate_file'])) {
    $str = '';
    for($i = 0; $i < 10; $i++) {
        $str .= "Number $i\n";
    }
    $name = 'file.txt';
    $path = '/var/www/html/';
    file_put_contents($path.$name, $str);
    echo $name;
}

ajax.html

<script type="text/javascript">
$.ajax({
    url: '/api.php', 
    data: {
        generate_file: true
    }
})
.done(function(name) {
    $('#results').append('<a href="/download.php?file=' + name + '" id="link">' + name + '</a>');
    document.getElementById('link').click(); // $('#link').click() wasn't working for me
    $('#link').remove();
});
</script>
<div id="results"></div>

【讨论】:

    猜你喜欢
    • 2012-04-26
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多