Austin E
Austin E

Reputation: 843

Sails.js Download File To Client

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)

Upvotes: 1

Views: 3992

Answers (2)

khushalbokadey
khushalbokadey

Reputation: 1152

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.

Upvotes: 1

tjadli
tjadli

Reputation: 800

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

Upvotes: 0

Related Questions