Sails.js下载文件到客户端
在我的Sails.js(v0.12)应用程序中,我们将文件生成到myApp/downloads/uuid-filename.ext中.但是我找不到如何将文件下载到客户端的可靠答案.
In my Sails.js(v0.12) app we generate a file into the myApp/downloads/uuid-filename.ext. However I cannot find a solid answer on how to download the file to client.
我的第一个想法是将uuid传递给用户,并允许他们从URL下载.但是,即使我知道完整的文件名,我也不确定如何从客户端访问文件.
My first idea was to pass the uuid to the user and allow them to download it from the URL. However I'm unsure how to access the files from the client even if I know the full file name.
第二个想法是将内容流式传输给用户,但是如果没有Express.js的"res.download()"功能,这似乎是不可能的.我在sails.js文档中找到了"res.attachment".但是,该示例丝毫没有帮助.
The second idea was to stream the content to the user, but without the Express.js "res.download()" function it seems impossible. I found "res.attachment" on the sails.js documentation. However the example was not helpful in the slightest.
如何从我的API(Sails.js v0.12)将文件下载到我的客户端(AngularJS)
How can I download a file from my API(Sails.js v0.12) to my client(AngularJS)
您实际上可以创建文件流并使用管道发送文件
You can actually create a stream of your file and use pipe to send it
这是工作代码
let filename = req.param("filename");
let filepath = req.param("filepath");
let file = require('path').resolve(sails.config.appPath+'//'+filepath)
if(fs.existsSync(file))
{
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
let filestream = fs.createReadStream(file);
filestream.pipe(res);
}else{
res.json({error : "File not Found"});
}
这已通过sailsJS(0.12)和AngularJS进行了测试
this is tested with sailsJS (0.12) and AngularJS