我尝试创建一个服务,该服务采用xlsx
模板文件并使用一些值响应填充的xlsx
文件。到目前为止我所做的是,
的index.html
<input name="file" type="file" onchange="callthis()"/>
的script.js
// callthis sends the file from client to server
function callthis() {
var formData = new FormData($(this).files[0]);
$.ajax({
url: '/uploadTemplate',
type: 'POST',
data: formData,
success: function (data) {
console.log(data);
alert(data)
},
cache: false,
contentType: false,
processData: false
});
}
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));
});
})
使用上面的代码,我可以上传文件并获得回复。成功方法打印出我添加了一些不可读字符的细节。但我无法下载该文件。
我如何下载文件。对于这种情况,有没有不同的更好的方法。
答案 0 :(得分:0)
您无法将下载附加到AJAX请求。您必须在AJAX响应中发送下载URL,然后让客户端脚本打开URL
在服务器中:
let response = {downloadUrl: Path.join(Locator.temp.temp, uploadedFilePath)}
res.json(response)
在客户端:
window.open(ajaxResponse.downloadUrl);