Skip to content

Instantly share code, notes, and snippets.

@halldorel
Last active March 4, 2019 20:20
Show Gist options
  • Save halldorel/723bbfbdae19335832f6c78f5d968649 to your computer and use it in GitHub Desktop.
Save halldorel/723bbfbdae19335832f6c78f5d968649 to your computer and use it in GitHub Desktop.
const folderName = filenamify(req.body.folderName);
const createSize = (file) => new Promise((resolve, reject) => {
// Returns a promise
console.log("Inside resize", file);
return sharp(file.buffer).resize(file.w, file.w, {
fit: sharp.fit.inside,
withoutEnlargement: true,
})
.toFormat('jpeg')
.toBuffer()
.then(resizedBuffer => {
console.log("resizedBuffer", resizedBuffer);
file.resizedBuffer = resizedBuffer;
resolve(file);
});
});
const resize = (file) => {
const outputSizes = [{ name: "large", w: 1200 },
{ name: "medium", w: 600 },
{ name: "small", w: 300 } ];
const buffer = file.buffer;
const originalName = file.originalname;
return outputSizes.map(outputSize => {
outputSize.buffer = buffer;
outputSize.originalName = originalName;
return outputSize;
});
};
const upload = (file) => new Promise((resolve, reject) => {
const fileName = folderName + "/" + file.name + "/" + new Date().getTime() + "_" + file.originalName;
const params = {
Bucket: bucketPictures,
Key: fileName,
Body: file.resizedBuffer, };
console.log("file: ", file);
console.log("params: ", params);
return s3.upload(params, (err, data) => {
if(err) {
console.error(err);
return reject(err);
}
resolve(data);
});
});
Promise.all(req.files.map(resize)).then( files => {
const resizedFlat = _.flatten(files);
return Promise.all(resizedFlat.map(createSize)).then( resizedFiles => {
return Promise.all(resizedFlat.map(upload)).then( uploadResults => {
res.status(201).json({ message: uploadResults });
});
});
}).catch(err => res.status(500).json({ err: err }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment