我正在创建一个带有节点js的csv文件,现在想将其下载到用户浏览器的默认下载位置。我们正在使用seneca和nodejs,并且csv文件正在保存在服务器上。现在当使用时会点击基于角度的前端的导出,节点将创建一个csv并将其下载到用户机器。我们怎样才能做到这一点?
答案 0 :(得分:1)
可以将使用Node.js生成的动态文件下载到浏览器的默认下载位置。有许多帖子概述了如何使用Express helper res.download()从服务器检索静态文件。根据您的问题,有一种方法可以实现您的要求。
通过对您的问题的解释,遵循以下流程:
节点处理数据并生成一个文件,无需第二次用户交互即可下载(用户单击“导出”并下载文件)。
客户端
//Export button
$("#exportBtn").click(function () {
//Code to generate data for the CSV and save it to the src variable
var src = csvData;
//Send the CSV data to Node for processing and file generation.
$.post("http://localhost:3000/submitcsv", { csv: src }, function (data) {
//Check the returned file name in data - this check depends on your needs; ie: regex
if (data) {
//request the file that is to be downloaded to the client. Optionally use $window.open()
window.location.href = "http://localhost:3000/app/" + data;
}
});
});
服务器
//Post data from the client
app.post('/submitcsv', function (req, res) {
var async = require('async');
var fs = require('fs');
var path = require('path');
var csvData = req.body.csv;
function processCSV(callback) {
//Code to create the csv file and a uniqueIdentifier
callback();
}
function finalize() {
//Save the CSV to the server. This is a specific location on the server in /app.
//You can use Express.static paths that suit your setup.
fs.writeFile('./app/temp/csvFile' + uniqueIdentifier + '.csv', buf, function (err) {
if (err) {
console.log(err);
res.send(500, "Something went wrong...");
}
else {
console.log("CSV file is saved");
//Send the file name and location back to the client
res.send('/temp/csvFile' + uniqueIdentifier + '.csv');
}
});
}
// After the CSV data is processed, save the file and send it to the client.
async.series([
processCSV
], finalize);
});
//Send the requested file back to the client
app.get('./app/:csvFile', function (req, res){
var c = req.params.csvFile;
res.download(c);
//Code to delete the file if it is temporary via fs.unlink
});
虽然上面的代码中没有显示简单,但建议以某种方式保护发送和接收此类数据的/ app路由。对受保护的路由使用Passport OIDCStrategy将类似于:
app.all('/app/*', function(req, res, next) {
//Check that the user has previously been authenticated
if (req.user){
next();
} else {
// require the user to log in
res.redirect("/login");
}
});
答案 1 :(得分:0)
我认为你不能...... Nodejs是服务器端...所以你放在Nodejs下的任何内容都会转到服务器...... 如果USER单击某个按钮或某个其他事件触发生成CSV文件的进程,则USER必须选择要保存的位置,否则文件将自动下载到USER&下指定的默认下载目录中。 #39;浏览器设置......