Skip to content

Instantly share code, notes, and snippets.

@ChunAllen
Forked from SylarRuby/userAvatar.js
Created November 22, 2018 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChunAllen/7a7e67eb1b4855826a85da52d5e5d6ca to your computer and use it in GitHub Desktop.
Save ChunAllen/7a7e67eb1b4855826a85da52d5e5d6ca to your computer and use it in GitHub Desktop.
NodeJs AWS S3 Upload
/**
* 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