从服务器下载文件(Nodejs Express> React) [英] Download file from server (Nodejs Express > React)
本文介绍了从服务器下载文件(Nodejs Express> React)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将文件(docx)发送给用户?
这是我的服务器代码:
how can i send a file(docx) to a user ? this is my server code :
app.get('/api/topic/file/:id', function (req, res, next) {
Topic.findByIdAndUpdate(req.params.id)
.exec()
.then((topic) => {
let filepath = topic.news_file[0]
console.log('filepath', filepath)
res.download(filepath, topic.name + '.docx', function (err) {
if (err) {
console.log('api get file err ', err);
} else {
// decrement a download credit, etc.
}
});
}).catch((err) => console.log('error', err));
})
这不会触发浏览器上的下载。我正在使用
作为前端。
在客户端上,我有一个按钮会在点击后触发:
this does not trigger a download on the browser. i am using react as front-end. on the client i have a button triggering this upon click :
handleDownload() {
if (this.state.lastClicked) {
fetch("/api/topic/file/" + this.state.lastClicked._id)
.then(results => {
console.log('results', results)
return results;
})
} else {
//somthings...
}
}
推荐答案
使用downloadjs找到解决方案。.
Found a solution using downloadjs..
var download = require("downloadjs")
async handleDownload() {
const res = await fetch("/api/topic/file/" + this.state.lastClicked._id);
const blob = res.blob();
download(blob, this.state.lastClicked.name + '.docx');
}
这篇关于从服务器下载文件(Nodejs Express> React)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文