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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19426623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:33:33  来源:igfitidea点击:

How to force file download upon jQuery AJAX success?

javascriptphpjqueryajaxdownload

提问by mike23

I'm generating a file dynamically in phplike this :

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

This data in then passed through jQuery.ajax

这些数据然后通过jQuery.ajax

I'd like to make it open a file download dialog upon success.

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

Right now I have this :

现在我有这个:

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

This does open a new window and display the raw file data. Instead I would like a download dialog to open.

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

回答by mts7

I'm not sure I have all the necessary information, but you could achieve the goal with 3 files.

我不确定我是否拥有所有必要的信息,但是您可以使用 3 个文件来实现目标。

download.php

下载.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

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

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>