Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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:, Key: destFileName, Body: ''};
let fileStream = fs.createReadStream(file.path);
fileStream.on('error', function(err) {
console.log('File Error', err);
uploadParams.Body = fileStream;
s3.upload(uploadParams, callback);
function deleteFile(filePath) {
fs.unlink(filePath, function (err) {
if (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)) {
response.write('{"status": 403, "message": "Expects Image File. Please try again."}');
return response.end();
uploadToS3(file, filename, function (error, data) {
if (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
You can’t perform that action at this time.