Last active
August 11, 2019 15:44
-
-
Save rotimi-best/65a51575e03c948e9410d619f6e357c3 to your computer and use it in GitHub Desktop.
How to upload and delete images from your AWS S3 bucket with NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// npm i aws-sdk | |
const AWS = require('aws-sdk') | |
// npm i uuid | |
const uuidv4 = require('uuid/v4'); | |
let s3 = null; | |
if (!s3) { | |
// Get these credential from the file you downloaded in your console | |
// https://help.bittitan.com/hc/en-us/articles/115008255268-How-do-I-find-my-AWS-Access-Key-and-Secret-Access-Key | |
s3 = new AWS.S3({ | |
accessKeyId: process.env.ACCESS_KEY_ID, | |
secretAccessKey: process.env.SECRET_ACCESS_KEY | |
}) | |
} | |
const uploadImage = (base64Data) { | |
return new Promise(async (resolve, reject) => { | |
if (!base64Data) { | |
reject('Base64 image is required'); | |
} | |
const photoId = uuidv4(); | |
const pureBase64 = base64Data.replace(/^data:image\/\w+;base64,/, "") | |
const imageBuffer = new Buffer(pureBase64, 'base64'); | |
const params = { | |
Bucket: process.env.BUCKET_NAME, // This is the name you gave to your bucket in your AWS console | |
Key: `${photoId}.jpg`, | |
Body: imageBuffer, | |
ContentEncoding: 'base64', | |
ContentType: 'image/jpeg' | |
}; | |
s3.upload(params, (s3Err, data) => { | |
if (s3Err) reject(s3Err); | |
const photoUrl = data.Location | |
// photoId - This should be saved in your database, then when you need to delete the image you just use it | |
resolve({ photoUrl, photoId }); | |
}); | |
}); | |
} | |
const deleteImage = (photoId) => { | |
return new Promise((resolve, reject) => { | |
if (!photoId) { | |
reject('PhotoId is required'); | |
} | |
try { | |
s3.deleteObject({ | |
Bucket: process.env.BUCKET_NAME, | |
Key: `${photoId}.jpg` | |
}, | |
error => error ? reject(error) : resolve(true) | |
) | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
} | |
module.exports = { | |
deleteImage, | |
uploadImage, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To make your images public:
Short answer: https://stackoverflow.com/a/4709391/8817146
Long answer: https://aws.amazon.com/premiumsupport/knowledge-center/read-access-objects-s3-bucket/