Skip to content

Instantly share code, notes, and snippets.

@BagrijRoman
Last active May 21, 2019 05:48
Show Gist options
  • Select an option

  • Save BagrijRoman/ea8b71d83a71762f92dd14996b6101cb to your computer and use it in GitHub Desktop.

Select an option

Save BagrijRoman/ea8b71d83a71762f92dd14996b6101cb to your computer and use it in GitHub Desktop.
const AWS = require('aws-sdk');
const request = require('request');
// define configs
const config = {
accessKeyId: '<S3_accessKeyId>',
secretAccessKey: '<S3_secretAccessKey>',
region: '<S3_region>',
signatureVersion: 'v4',
S3ImagesPathPrefix: 'profileImages',
bucketName: '<bucket_name>',
};
// Init S3
const S3 = new AWS.S3({
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.region,
signatureVersion: config.signatureVersion,
});
const loadImageFromUrlToBuffer = (imageUrl) => new Promise((res, rej) => {
try {
const reqOptions = { url: imageUrl, method: 'get', encoding: null };
request(reqOptions, (error, response, body) => {
if (error) {
throw error;
}
// log success download or some additional actions here
return res(body);
});
} catch (err) {
// log download fail here or some additional actions here
rej(err);
}
});
const storeBufferedImageToS3 = (buffer, fileName) => new Promise((resolve, rej) => {
try {
const params = {
Bucket: config.bucketName,
Key: `${config.S3ImagesPathPrefix}/${fileName}.jpeg`,
Body: buffer,
ACL:'public-read',
ContentType: 'image/jpeg',
};
S3.upload(params, (err, res) => {
if (err) {
throw err;
}
// log success upload or some additional actions here
resolve(res.Location);
});
} catch (err) {
// log upload fail here or some additional actions here
rej(err);
}
});
// userId will be used as unique file name
const storeSocialNetworkImageToS3 = async (imageUrl, userId) => {
try {
const imageFileBuffer = await loadImageFromUrlToBuffer(imageUrl);
const s3ImageLink = await storeBufferedImageToS3(imageFileBuffer, userId);
// log sucess action or some additional code here
return s3ImageLink;
} catch (err) {
// error handling functionnality can be here
throw err;
}
};
// fn call sample
const userImageLink = '<valid image link>';
const userId = '<some id string>';
const S3UserImageLink = await storeSocialNetworkImageToS3(userImageLink, userId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment