简体   繁体   English

jQuery AJAX成功后如何强制文件下载?

[英]How to force file download upon jQuery AJAX success?

I'm generating a file dynamically in php like 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. 相反,我想打开一个下载对话框。

I'm not sure I have all the necessary information, but you could achieve the goal with 3 files. 我不确定我是否拥有所有必要的信息,但是您可以通过3个文件来实现目标。

download.php 的download.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM