Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - 使用ajax请求下载文件(download file using an ajax request)

I want to send an "ajax download request" when I click on a button, so I tried in this way:

(当我单击按钮时,我想发送“ ajax下载请求”,因此我尝试了这种方式:)

javascript:

(javascript:)

var xhr = new XMLHttpRequest();
xhr.open("GET", "download.php");
xhr.send();

download.php:

(download.php:)

<?
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename= file.txt");
header("Content-Transfer-Encoding: binary");    
readfile("file.txt");
?>

but doesn't work as expected, how can I do ?

(但是没有按预期工作,我该怎么办?)

Thank you in advance

(先感谢您)

  ask by Manuel Di Iorio translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update April 27, 2015

(2015年4月27日更新)

Up and coming to the HTML5 scene is the download attribute .

(进入HTML5场景的是download属性 。)

It's supported in Firefox and Chrome, and soon to come to IE11.

(Firefox和Chrome都支持该功能,不久之后将成为IE11。)

Depending on your needs, you could use it instead of an AJAX request (or using window.location ) so long as the file you want to download is on the same origin as your site.

(根据您的需求,您可以使用它来代替AJAX请求(或使用window.location ),只要您要下载的文件与您的站点位于同一来源即可。)

You could always make the AJAX request/ window.location a fallback by using some JavaScript to test if download is supported and if not, switching it to call window.location .

(通过使用一些JavaScript来测试是否支持download可以始终使AJAX request / window.location回退,如果不支持,则将其切换到call window.location 。)

Original answer

(原始答案)

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download.

(您不能有AJAX请求打开下载提示,因为您实际上必须导航到文件以提示下载。)

Instead, you could use a success function to navigate to download.php.

(相反,您可以使用成功函数导航到download.php。)

This will open the download prompt but won't change the current page.

(这将打开下载提示,但不会更改当前页面。)

$.ajax({
    url: 'download.php',
    type: 'POST',
    success: function() {
        window.location = 'download.php';
    }
});

Even though this answers the question, it's better to just use window.location and avoid the AJAX request entirely.

(即使这回答了问题,还是最好只使用window.location并完全避免AJAX请求。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...