node.js - 从服务器下载文件(Nodejs Express > React)
问题描述
我如何向用户发送文件(docx)?这是我的服务器代码:
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));
})
这不会触发浏览器上的下载。我正在使用反应作为前端。在客户端我有一个按钮在点击时触发它:
handleDownload() {
if (this.state.lastClicked) {
fetch("/api/topic/file/" + this.state.lastClicked._id)
.then(results => {
console.log('results', results)
return results;
})
} else {
//somthings...
}
}
解决方案
使用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');
}
推荐阅读
- proxy - 如何将 Cronet Native 与代理一起使用?
- arrays - 过滤对象中的数组时过滤器不起作用
- reactjs - 我可以在另一条私人路线中拥有其他私人路线吗?反应式
- installation - Leiningen 只在一个目录中运行
- python - 遍历字典,设置复制警告
- python - 获取 TypeError:“CRS”类型的参数不能与 OSMnx 包一起迭代
- android - Android:handleDeeplink() 后导航 Deeplink 未失效
- r - plot_forest 命令给了我这个错误:定义子组的变量不是分类的
- python - 根据条件从两个数据帧之一分配行的快速方法
- webrtc - Kurento在线发布