node.js - 后端的 ExpressJS res.download() + 前端的 fetch
问题描述
对不起,如果这是一个菜鸟问题,但我无法让它工作......
我有一个使用 NodeJS 和 ExpressJs 并提供一些使用 VueJS 构建的静态内容的后端。
我想允许用户下载文件,所以我正在尝试实现它。
在后端,这是代码
app.get('/download', function (req, res, next) {
let queryparams = req.query;
if (queryparams.filename) {
try {
res.download(queryparams.filename);
} catch (error) {
console.log('Unable to read ' + queryparams.filename + ' file. Please check');
res.write('Unable to read ' + queryparams.filename + ' file. Please check');
res.status(501);
}
res.end();
} else {
next();
}
});
在前端,我尝试使用 downloadjs npm 包,但它不起作用,而且,我需要它吗?
fetch(`https://${servername}/download?filename=` + data.filename)
.then((response) => response.blob())
.then((blob) => downloadjs(blob, data.filename));
任何帮助将不胜感激
鲍勃
解决方案
这就是我在我的 express 应用程序上实现下载的方式。当用户访问此特定 URL 时,他们将自动下载该文件。这是我正在从事的项目的代码片段。希望能帮助到你
router.get('/frontliners/file.csv', function (req, res) {
controller.airtableFrontliners((output) => {
res.status(200)
const file = `${__dirname}/data.csv`; // Get the path of the file
res.download(file);
})
});
推荐阅读
- ios - 检索场景中所有可用的 SCNbox、SCNNode 并显示、隐藏它们
- php - 在 foreach 循环中更新数组数据的问题
- c# - DatagridView C# 列的总和
- vba - 公式太长 - 达到字符限制 - VBA 可以工作吗?
- android - 两个 Android 手机/设备的设备 ID 可以相同吗?
- pandas - 用 Pandas 绘制分类数据的摘要
- uima - Apache UIMA 字典注释器
- c# - ASP.NET:摆脱 Gridview 中的“”
- php - 设置循环内来自 JSON 的 PHP 回显项的字符限制
- .net - Podio .Net API Importer 值检查