如何使用nodejs从项目/特定位置下载文件?

时间:2021-03-09 23:30:01

This may be a dumb question but I am lil confused, my requirement is I should be able to download an excel template on a click event, I thought I will put that excel template in some folder(docs) in my backend code(instead of generating it dynamically) and download that. Is that possible, if yes how? I am using express and node.

这可能是一个愚蠢的问题,但我很困惑,我的要求是我应该能够在点击事件上下载excel模板,我想我会把这个excel模板放在我的后端代码(而不是动态生成它)的某个文件夹(docs)中,然后下载它。有可能吗?我使用的是express和node。

1 个解决方案

#1


1  

It is possible. Probably you use Express framework. Express can serve static files under '/public' folder. When user connect to this file, her/his browser will download file. But some browser can view files online. For example, Chrome can open PDF files. If you want to force to download file you can use this simple code;

这是可能的。可能你用的是Express框架。Express可以在'/public'文件夹下提供静态文件。当用户连接到该文件时,其浏览器将下载该文件。但是有些浏览器可以在线查看文件。例如,Chrome可以打开PDF文件。如果你想强制下载文件,你可以使用这个简单的代码;

app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
  res.download(file); // Set disposition and send it.
});

#1


1  

It is possible. Probably you use Express framework. Express can serve static files under '/public' folder. When user connect to this file, her/his browser will download file. But some browser can view files online. For example, Chrome can open PDF files. If you want to force to download file you can use this simple code;

这是可能的。可能你用的是Express框架。Express可以在'/public'文件夹下提供静态文件。当用户连接到该文件时,其浏览器将下载该文件。但是有些浏览器可以在线查看文件。例如,Chrome可以打开PDF文件。如果你想强制下载文件,你可以使用这个简单的代码;

app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
  res.download(file); // Set disposition and send it.
});