Javascript 如何在请求中发送文件并在响应中下载文件而无需重定向
我试图创建一个服务,它接受一个Javascript 如何在请求中发送文件并在响应中下载文件而无需重定向,javascript,jquery,node.js,Javascript,Jquery,Node.js,我试图创建一个服务,它接受一个xlsx模板文件,并用一些值响应一个填充的xlsx文件。到目前为止,我所做的是 index.html <input name="file" type="file" onchange="callthis()"/> serverRouter.js router.post('/uploadTemplate', function(req, res, next){ let uploadedFilePath = null; // I'm usin
xlsx
模板文件,并用一些值响应一个填充的xlsx
文件。到目前为止,我所做的是
index.html
<input name="file" type="file" onchange="callthis()"/>
serverRouter.js
router.post('/uploadTemplate', function(req, res, next){
let uploadedFilePath = null;
// I'm using multer for handling formdata in the server
var upload = multer({ dest: Locator.temp.temp });
//configure the multer
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, Locator.temp.temp);
},
filename: function (req, file, callback) {
uploadedFilePath = file.fieldname + '-' + Date.now() + '.xlsx';
callback(null, uploadedFilePath);
}
});
var upload = multer({ storage : storage}).single('file');
//in here i am uploading the file.
//and reading the file ugin XLSX modules.
//doing some changes to xlsx json object
//and write the data to a file in a temp folder
//i'm using res.download method to send downloadable file back to client
res.download(Path.join(Locator.temp.temp, uploadedFilePath));
});
})
使用以上代码,我可以上传文件并获得响应。success方法打印出我添加的一些不可读字符的细节。但我无法下载该文件
如何下载该文件。对于这种情况,有没有其他更好的方法。您不能将下载附加到AJAX请求。您必须在AJAX响应中发送下载URL,然后让客户端脚本打开URL 在服务器中:
let response = {downloadUrl: Path.join(Locator.temp.temp, uploadedFilePath)}
res.json(response)
在客户端:
window.open(ajaxResponse.downloadUrl);
可能重复的nope。当我们导航到url时,它正在工作。但在这种情况下,我不想导航到url
window.open(ajaxResponse.downloadUrl);