Skip to content

Instantly share code, notes, and snippets.

@davidostermann
Last active May 4, 2017 19:32
Show Gist options
  • Save davidostermann/3b81ba3664d2d9851948d0a391d33078 to your computer and use it in GitHub Desktop.
Save davidostermann/3b81ba3664d2d9851948d0a391d33078 to your computer and use it in GitHub Desktop.
HapiJs route + controller : S3 Bucket get signed request
const Boom = require('boom');
const Aws = require('aws-sdk');
const S3_BUCKET = process.env.S3_BUCKET_NAME;
server.routes = [
{
method: 'GET',
path: '/upload/request',
config: {
handler: getS3SignedRequest,
description: 'Get S3 signed url'
}
}
];
const getS3SignedRequest = (request, reply) => {
const s3 = new Aws.S3();
const fileName = request.query['file-name'];
const fileType = request.query['file-type'];
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err){
console.log(err);
return reply(Boom.badRequest(err));
}
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
return reply(returnData).code(200);
});
};
import fetch from 'isomorphic-fetch'
export const uploadFile = (file) => {
return getS3SingnedRequest(file)
.then((response) => {
return uploadFileToS3(file, response );
});
};
const getS3SignedRequest = (file) => {
return fetch(`/api/upload/request?file-name=${encodeURIComponent(file.name)}&file-type=${file.type}`, {
credentials: 'same-origin',
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.catch((err) => {
alert('Could not get signed URL.');
})
};
const uploadFileToS3 = (file, signedObj) => {
return fetch(signedObj.signedRequest, {
method: 'PUT',
body: file
})
.then((response) => {
return signedObj.url;
})
.catch((err) => {
alert('Could not upload file.');
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment