Created
September 9, 2014 03:34
-
-
Save jobsamuel/2210ef85515e3e1b3d0f to your computer and use it in GitHub Desktop.
Uploading and Image to an existing AWS S3 Bucket
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
// File System node module. | |
var fs = require('fs'); | |
// Amazon SDK node module. | |
var AWS = require('aws-sdk'); | |
// Read a file in the project folder that contains your AWS credentials. | |
// On a production server, you would want to reference the credentials using environmental variables. | |
AWS.config.loadFromPath('config.json'); | |
// Connect directly to a bucket, instantiating an AWS.S3 object by passing in the bucket name as a parameter. | |
var s3Bucket = new AWS.S3({ params: {Bucket: 'beverages'}}); | |
// Asynchronously reads the entire contents of a file. | |
// The first argument is a String (filename) and the second a callback. | |
// The callback is passed two arguments (err, data), where data is the contents of the file. | |
fs.readFile('pepsi.jpg', function(err, imgFile) { | |
if (err) throw err; | |
// In order to upload an image, you can use the putObject method that takes | |
// a data and callback function as arguments. The data should contain a Key, Body and ContentType property. | |
// The Key should contain the name of the image, and the Body should contain the image file itself, | |
// and the ContentType should contain the data media type (http://en.wikipedia.org/wiki/Internet_media_type). | |
// The callback function takes an error and data as arguments that you can use to check the status of the uploaded file. | |
var img = {Key: "pepsi.jpg", Body: imgFile, ContentType: 'image/jpeg'}; | |
s3Bucket.putObject(img, function(err, data){ | |
if (err) | |
{ console.log('Error: ', err.message); | |
} else { | |
console.log('Image uploaded succesfully!'); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment