0π
β
To Download a file from amazon S3
follow these steps
- Install aws sdk using this command
npm install aws-sdk
- 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()
Source:stackexchange.com