Download AWS S3 file from EC2 instance using Node.

2019-09-10 22:37发布

问题:

I am trying to download file from Amazon S3 bucket from my Node.js hosted application.

var folderpath= process.env.HOME || process.env.USERPROFILE  // tried using os.homedir() also

var filename  =  'ABC.jpg';
var filepath = 'ABC';

 AWS.config.update({
    accessKeyId: "XXX",
    secretAccessKey: "XXX",
    region: 'ap-southeast-1'
 });

  var DOWNLOAD_DIR = path.join(folderpath, 'Downloads/');

    var s3 = new AWS.S3();
    var s3Params = {Bucket: filepath,Key: filename, };

    var file = require('fs').createWriteStream(DOWNLOAD_DIR+ filename);
    s3.getObject(s3Params).createReadStream().pipe(file);

This code works fine on localhost but does not work from instance because on instance folderpath returns "/home/ec2-user" instead of path of downloads folder of user machine i.e something like "C:\Users\name".

Please suggest me how can I download file to user's machine? How to get path of user's home directory from ec2 instance?

Thank you.

回答1:

You can use express to create http server and APIs. You can find numerous tutorials on get started with Express.js. After the initial setup of express.js is done, you can do something like this in node.js code:

AWS.config.update({
   accessKeyId: "XXX",
   secretAccessKey: "XXX",
   region: 'ap-southeast-1'
});
var s3 = new AWS.S3();

app.get('/download', function(req, res){
  var filename = 'ABC.jpg';
  var filepath = 'ABC';
  var s3Params = {Bucket: filepath, Key: filename};
  var mimetype = 'video/quicktime'; // or whatever is the file type, you can use mime module to find type

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  // Here we are reading the file from S3, creating the read stream and piping it to the response.
  // I'm not sure if this would work or not, but that's what you need: Read from S3 as stream and pass as stream to response (using pipe(res)).
  s3.getObject(s3Params).createReadStream().pipe(res);
});

Once this is done, you can call this API /download, and then download the file on user's machine. Depending on the framework or library (or plain javascript) which you are using in front end, you can download the file using this /download api. Just google, how to download file using XYZ (framework).