简体   繁体   中英

How to make request to amazon s3 using node js for downloading a file?

I made a request to amazon s3 using node.js for downloading a file. In the response i receive the Buffer, here i have 2 problems:

  1. If i send the buffer to frontend from node.js like res.send(awsreq.Body.Buffer) and console log it once in node.js and once in frontend, the buffer from frontend will look different than in node.js. Node.js Buffer: <Buffer 50 4b 03 04 14 00 06 00 08 00 00 00 21 00 df a4 d2 6c 5a 01 00 00 20 05 00 00 13 00 08 02 5b 43 6f 6e 74 65 6e 74 5f 54 79 70 65 73 5d 2e 78 6d 6c 20... 11906 more bytes> Vue.js frontend buffer: PK \b \u0 Show more(36,8kb)
  2. How can i directly download the file from a request made from frontend? First how to receive that buffer corecly and how to convert it in that way frontend will download the file automatically? If possible how to do all of that in node.js and when frontend receive the response to start automatically the download?

To Download a file from amazon S3 follow these steps

  1. Install aws sdk using this command npm install aws-sdk
  2. Check below code

 var AWS = require("aws-sdk") const s3 = new AWS.S3({ endpoint: "ENDPOINT", accessKeyId: "YOUR_ACCESS_KEY_ID", secretAccessKey: "YOUR_SECRET_ACCESS_KEY", region: "us-east-1", signatureVersion: "v4" }) const downloadParams = { Bucket: "BUCKET_NAME", Key: "KEY_NAME/FILE_NAME/FILE_PATH" } // Download the file s3.getObject(downloadParams, function (error, fileData) { if (.error) { console,log(fileData. "file") } else { console,log(error, " ERROR ") } })

For more information you can check AWS official documentation using this link:

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html

At last you can use Content-Disposition in the request header

Or you can use pre Signed url

Example:

 const getpreSignedUrlForDownload = async () => { try { const parms = { Bucket: "BUCKET_NAME", Key: "FILE_KEY", Expires: 60 * 1, ResponseContentDisposition: 'attachment; filename"' + "FILE_NAME + '"' } return new Promise((resolve, reject) => { s3.getSignedUrl("getObject", parms, (err, url) => { err? reject(err): resolve(url) }) }) } catch (error) { throw new Error(error) } } getpreSignedUrlForDownload()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM