Sails.js下载文件到客户端 [英] Sails.js Download File To Client

查看:105
本文介绍了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

这篇关于Sails.js下载文件到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆