javascript - 如何在 jQuery AJAX 成功时强制下载文件?

标签 javascript php jquery ajax download

我正在 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);
}

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

最佳答案

我不确定我是否拥有所有必要的信息,但您可以使用 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>

关于javascript - 如何在 jQuery AJAX 成功时强制下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19426623/

相关文章:

javascript - javascript中文件名的分割

php - 执行此 UPDATE 查询的最佳方法

javascript - 如何在 JSFiddle 上创建具有可调整大小的行和列(如 HTML、CSS、JS 框)的表格?

PHP 无法初始化 Mysqli

jquery - 当我选择特定选项 jQuery 时如何删除类

javascript - 将 JSON 文件加载到 highcharts 中以绘制折线图

javascript - 升级到 jQuery 1.6.2 后,globalEval 在页面上尝试执行 javascript 时抛出错误

javascript - 如何循环遍历 hl7 消息中的所有标题?

Polymer 元素注册前的 JavaScript 初始化

php - 无法从 PHP、SQL 中的下拉列表中获取所选值