Sails.js Download File To Client

爱⌒轻易说出口 提交于 2019-12-02 09:48:04

问题


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.

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.

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.

How can I download a file from my API(Sails.js v0.12) to my client(AngularJS)


回答1:


You can actually create a stream of your file and use pipe to send it

here is a working code

    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"});
    }

this is tested with sailsJS (0.12) and AngularJS




回答2:


The easiest way which I could think of is generate the file in downloads folder inside assets folder.

This way if you provide the download link as http://<url>/downloads/<uuid>.<ext>, it will automatically download if the file exists, else will throw 404.



来源:https://stackoverflow.com/questions/50142797/sails-js-download-file-to-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!