Created
April 19, 2013 16:00
-
-
Save johnschimmel/5421308 to your computer and use it in GitHub Desktop.
ExpressJS file upload to S3
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
exports.new_photo = function(req, res){ | |
// Get File upload information | |
var filename = req.files.image.filename; // actual filename of file | |
var path = req.files.image.path; //will be put into a temp directory | |
var mimeType = req.files.image.type; // image/jpeg or actual mime type | |
// Create a new blog post | |
var photoPost = new Photo(); // create Blog object | |
photoPost.title = req.body.title; | |
photoPost.urltitle = req.body.title.toLowerCase().replace(/[^\w ]+/g,'').replace(/ +/g,'_') | |
photoPost.caption = req.body.caption; | |
// any file upload? | |
console.log("about to upload") | |
// 2) create file name with logged in user id + cleaned up existing file name. function defined below. | |
cleanedFileName = cleanFileName(filename); | |
// 3a) We first need to open and read the image upload into a buffer | |
fs.readFile(path, function(err, file_buffer){ | |
// pick the Amazon S3 Bucket | |
var s3bucket = new AWS.S3({params: {Bucket: 'dwd_uploads'}}); | |
// Set the bucket object properties | |
// Key == filename | |
// Body == contents of file | |
// ACL == Should it be public? Private? | |
// ContentType == MimeType of file ie. image/jpeg. | |
var params = { | |
Key: cleanedFileName, | |
Body: file_buffer, | |
ACL: 'public-read', | |
ContentType: mimeType | |
}; | |
// Put the Object in the Bucket | |
s3bucket.putObject(params, function(err, data) { | |
if (err) { | |
console.log(err) | |
} else { | |
console.log("Successfully uploaded data to s3 bucket"); | |
// add image to blog post | |
photoPost.image = cleanedFileName; | |
} | |
photoPost.save(); | |
res.redirect('/'); | |
}); | |
}); | |
}; |
I was confused about the attributes Key
in params when I read the documentation then I came across this gist. Thanks.
You should handle the case fs.readFile fails.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome code!,
But the code deos not have a policy doc and signature.
deos it mean i don't need it for anonymous uploads to my amazon s3 bucket ?.
Thanks