Skip to content

Instantly share code, notes, and snippets.

@richwednesday
Created December 28, 2017 19:46
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save richwednesday/ea0c744543d2db8c86f6cf5469c53330 to your computer and use it in GitHub Desktop.
Save richwednesday/ea0c744543d2db8c86f6cf5469c53330 to your computer and use it in GitHub Desktop.
Image Upload to S3 From Node.js
const http = require("http");
const https = require("https");
const AWS = require('aws-sdk');
const formidable = require("formidable");
const uuid = require("uuid");
let server = http.createServer(launch);
let s3 = new AWS.S3({
// s3 credentials
});
function uploadToS3(file, destFileName, callback) {
let uploadParams = {Bucket: config.bucket.name, Key: destFileName, Body: ''};
let fileStream = fs.createReadStream(file.path);
fileStream.on('error', function(err) {
console.log('File Error', err);
});
uploadParams.Body = fileStream;
deleteFile(file.path);
s3.upload(uploadParams, callback);
}
function deleteFile(filePath) {
fs.unlink(filePath, function (err) {
if (err) {
console.error(err);
}
console.log('Temp File Delete');
});
}
function launch (request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (error, fields, files) {
let fileId = uuid.v4();
let filename = `user-photos/${fileId}.jpg`;
let file = files.selfie;
if (!/^image\/(jpe?g|png)$/i.test(file.type)) {
deleteFile(file.path);
response.write('{"status": 403, "message": "Expects Image File. Please try again."}');
return response.end();
}
uploadToS3(file, filename, function (error, data) {
if (error) {
console.log(error);
response.write('{"status": 442, "message": "Yikes! Error uploading your photo. Please try again."}');
return response.end();
}
else if (data) {
response.write(JSON.stringify({status: 200, uri: data.Location}));
return response.end();
}
else {
response.write('{"status": 442, "message": "Yikes! Error saving your photo. Please try again."}');
return response.end();
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment