-
-
Save piggydoughnut/028ffa9388e0d6302dcd3a48c5d83e66 to your computer and use it in GitHub Desktop.
NodeJs AWS S3 Upload
This file contains hidden or 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
/** | |
* This gist was inspired from https://gist.github.com/homam/8646090 which I wanted to work when uploading an image from | |
* a base64 string. | |
* This code is used in my startup, Zired. | |
* Web: http://zired.io | |
*/ | |
// You can either "yarn add aws-sdk" or "npm i aws-sdk" | |
const AWS = require('aws-sdk') | |
// Configure AWS with your access and secret key. I stored mine as an ENV on the server | |
// ie: process.env.ACCESS_KEY_ID = "abcdefg" | |
AWS.config.update({ accessKeyId: process.env.ACCESS_KEY_ID, secretAccessKey: process.env.SECRET_ACCESS_KEY }); | |
// Create an s3 instance | |
const s3 = new AWS.S3(); | |
// Ensure that you POST a base64 data to your server. | |
// Let's assume the variable "base64" is one. | |
const base64Data = new Buffer(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64') | |
// Getting the file type, ie: jpeg, png or gif | |
const type = base64.split(';')[0].split('/')[1] | |
// Generally we'd have a userId associated with the image | |
// For this example, we'll simulate one | |
const userId = 1; | |
// With this setup, each time your user uploads an image, will be overwritten. | |
// To prevent this, use a unique Key each time. | |
// This won't be needed if they're uploading their avatar, hence the filename, userAvatar.js. | |
const params = { | |
Bucket: process.env.S3_BUCKET, | |
Key: `${userId}.${type}`, // type is not required | |
Body: base64Data, | |
ACL: 'public-read', | |
ContentEncoding: 'base64', // required | |
ContentType: `image/${type}` // required. Notice the back ticks | |
} | |
// The upload() is used instead of putObject() as we'd need the location url and assign that to our user profile/database | |
// see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property | |
s3.upload(params, (err, data) => { | |
if (err) { return console.log(err) } | |
// Continue if no error | |
// Save data.Location in your database | |
console.log('Image successfully uploaded.'); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment