使用ajax请求下载文件 [英] download file using an ajax request

查看:160
本文介绍了使用ajax请求下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送一个ajax下载请求,当我点击一个按钮,所以我这样尝试:

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

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

推荐答案

更新2015年4月27日

来到HTML5场景是下载属性。 Firefox和Chrome中的支持,很快就会来到IE11。根据您的需要,您可以使用它而不是AJAX请求(或使用 window.location ),只要您要下载的文件与您的

Up and coming to the HTML5 scene is the download attribute. It's supported in Firefox and Chrome, and soon to come to 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.

您可以随时使用 window.location https://stackoverflow.com/questions/12112844/how-to-detect-support-for-the-html5-download-attribute\">一些JavaScript ,以测试下载支持,如果没有,请切换到 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.

原始答案

您不能有AJAX请求打开下载提示,因为您必须导航到该文件才能提示下载。相反,您可以使用成功功能导航到download.php。这将打开下载提示,但不会更改当前页面。

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to 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';
    }
});

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

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

这篇关于使用ajax请求下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆