在ajax成功node.js上下载文件 [英] Download file on ajax success node.js
问题描述
我正在使用node.js构建一个应用程序,该应用程序需要允许用户下载.csv文件.
I am building an app using node.js that needs to allow the user to download a .csv file.
问题-用户单击按钮时,应用程序不会将文件作为附件发送到客户端.但是,如果客户端直接转到API链接,则会下载该文件.例如. -如果用户转到localhost:3000/api/exportmetric
,则该文件将作为附件发送到客户端.但是,如果该路由是作为AJAX请求命中的,则什么也不会发生.
The problem - the app does not send a file to the client as an attachment when the user clicks a button. HOWEVER, if the client goes directly to the API link, the file will download. E.g. - if the user goes to localhost:3000/api/exportmetric
, the a file will be sent to the client as an attachment. But if that route is hit as an AJAX request, nothing happens.
用户流:
1)用户单击一个按钮
1) User clicks a button
2)应用向服务器发出AJAX GET请求
2) App makes AJAX GET request to server
3)服务器从数据库中检索数据
3) Server retrieves data from a database
4)服务器将数据解析为.csv文件
4) Server parses the data into a .csv file
5)服务器将文件发送回客户端以作为附件下载.
5) Server sends file back to the client to download as an attachment.
我的代码:
client.js
client.js
$("#export_velocity").click(function(e) {
console.log('export to velocity hit');
$.ajax({
url: 'http://localhost:3001/api/exportmetric',
type: 'GET',
success: function(response) {
console.log(response);
},
error: function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
});
});
server.js
server.js
router.get('/api/exportmetric', function(req, res) {
console.log('export metric hit');
var fields = ['first_name', 'last_name', 'age'];
var fieldNames = ['First Name', 'Last Name', 'Age??'];
var people = [
{
"first_name": "George",
"last_name": "Lopez",
"age": "31"
}, {
"first_name": "John",
"last_name": "Doe",
"age": "15"
}, {
"first_name": "Jenna",
"last_name": "Grassley",
"age": "44"
}
];
json2csv({ data: people, fields: fields, fieldNames: fieldNames }, function(err, csv) {
res.setHeader('Content-disposition', 'attachment; filename=file.csv');
res.set('Content-Type', 'text/csv');
console.log(csv)
res.status(200).send(csv);
});
});
推荐答案
基本上有两种流行的下载文件的方式.
There are basically two popular ways to download a file.
1.设置window.location
1. Set window.location
将window.location
设置为下载网址将下载文件.
Setting window.location
to the download url will download the file.
window.location = '/path/to/download?arg=1';
与此版本略有不同的是打开带有下载路径的新标签页
A slightly different version of this is to open a new tab with the download path
window.open('/path/to/download', '_self');
2.虚拟链接单击
使用HTML5,您可以指定链接的download
属性.单击链接(甚至以编程方式)将触发该URL的下载.链接甚至不需要成为DOM的一部分,您可以动态地使它们成为链接.
With HTML5, you can specify the download
attribute of a link. Clicking the link (even programmatically) will trigger a download of the url. The links don't even need to be part of the DOM, you can make them dynamically.
var link = document.createElement('a');
link.href = '/path/to/download';
link.download = 'local_filename.csv';
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
并非所有浏览器都支持此功能,因此,即使您想使用此方法,也必须放弃对某些浏览器的支持或回退到第一种方法.
This isn't supported in all browsers, so even if you want to use this method, you'll have to drop support for some browsers or fallback to the first method.
幸运的是,这个出色的答案引用了一个很棒的小型js
库,该库已经完成了所有这些操作- http://pixelscommander.com/polygon/downloadjs/#.VrGw3vkrKHv
Luckily, this excellent answer references an awesome little js
library that does all this already -- http://pixelscommander.com/polygon/downloadjs/#.VrGw3vkrKHv
downloadFile('/path/to/download');
两步下载
您经常会看到的另一种约定是两步下载,即以已知的URL将信息发送到服务器,然后服务器发回生成的URL或ID,可用于下载文件.
Another convention you'll often see is a two step download, where information is sent to the server at a known url, and the server sends back a generated url or id that can be used to download the file.
如果您希望url是可以共享的内容,或者必须将大量参数传递给下载生成器,或者只是想通过POST
请求进行操作,则这很有用.
This can be useful if you want the url to be something that can be shared, or if you have to pass a lot of parameters to the download generator or just want to do it via a POST
request.
$.ajax({
type: 'POST',
url: '/download/path/generator',
data: {'arg': 1, 'params': 'foo'},
success: function(data, textStatus, request) {
var download_id = data['id'];
// Could also use the link-click method.
window.location = '/path/to/download?id=' + download_id;
}
});
这篇关于在ajax成功node.js上下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!