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

查看:166
本文介绍了使用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现场的<一个href="http://webdesign.tutsplus.com/tutorials/quick-tip-using-the-html5-download-attribute--cms-23880">download属性。它支持在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.

您总是可以让AJAX请求/ window.location的后备使用<一个href="http://stackoverflow.com/questions/12112844/how-to-detect-support-for-the-html5-download-attribute">some 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, 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';
    }
});

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

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