7

Have looked at all the tutorials on how to download files from S3 to local disk. I have followed all the solutions and what they do is download the file to the server and not to the client. The code I currently have is

app.get('/download_file', function(req, res) {
  var file = fs.createWriteStream('/Users/arthurlecalvez/Downloads/file.csv');
  file.on('close', function(){console.log('done'); });
  s3.getObject({ Bucket: 'data.pool.al14835', Key: req.query.filename }).on('error', function (err) {
   console.log(err);
   }).on('httpData', function (chunk) {
      file.write(chunk);
   }).on('httpDone', function () {
       file.end();
   }).send();

  res.send('success')

 })

How do I then send this to the client so that it is downloaded onto their device?

Adil B
  • 14,635
  • 11
  • 60
  • 78
Arthur Le Calvez
  • 413
  • 2
  • 7
  • 17

4 Answers4

11

you can use SignedURL Like that

var params = {Bucket: bucketname , Key: keyfile , Expires: 3600 , ResponseContentDisposition :  `attachment; filename="filename.ext"` };
var url = s3.getSignedUrl('getObject', params);

the generated link will force download with the name filename.ext

Alsemany
  • 445
  • 1
  • 5
  • 13
10

S3 supports the ability to generate a pre-signed URL via the AWS Javascript API. Users can then GET this URL to download the S3 object to their local device.

See this question for a Node.js code sample.

Adil B
  • 14,635
  • 11
  • 60
  • 78
0

If you have the file URL you can do it like that,

new Observable((observer) => {
      var xhr = new XMLHttpRequest();
      xhr.open("get", fileURL, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (xhr.readyState === 4) {
          observer.next(xhr.response);
          observer.complete();
        }
      };
      xhr.send();
    }).subscribe((blob: any) => {
      let link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = elem.material.driverUrl;
      link.click();
    });

The file URL is: https://BucketName.Region.amazonaws.com/Key Just replace with your Bucket name, Region and Key

Amr Omar
  • 399
  • 5
  • 12
0

You can use the res.download method http://expressjs.com/en/api.html#res.download ?

D. Richard
  • 460
  • 3
  • 12