Skip to content

Instantly share code, notes, and snippets.

@lcolsant
Forked from nyx-code/FileUpload.js
Last active February 17, 2021 06:37
Show Gist options
  • Select an option

  • Save lcolsant/185703a670bed4c8ec6c12f875cb4dc2 to your computer and use it in GitHub Desktop.

Select an option

Save lcolsant/185703a670bed4c8ec6c12f875cb4dc2 to your computer and use it in GitHub Desktop.
This NodeJS API which will upload files onto the AWS S3 Bucket. Video -> https://youtu.be/TtuCCfren_I
require('dotenv/config')
const express = require('express')
const multer = require('multer')
const sharp = require('sharp');
const AWS = require('aws-sdk')
// const uuid = require('uuid/v4')
const app = express()
const port = 3000
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_KEY
});
const storage = multer.memoryStorage();
//filter non-photo objects
const multerFilter = (req, file, cb) => {
if(file.mimetype.startsWith('image')) {
cb(null, true)
} else {
cb(new Error('Must upload an image.'),false)
}
}
//resize image to desired dimensions
const resizePhoto = async (req, res, next) => {
try{
if (!req.file) return next();
await sharp(req.file.buffer)
.resize(640,400) //1.6:1 ratio
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toBuffer()
.then(buffer=>{
req.file.buffer = buffer});
next();
}catch(err){
console.log(err);
new Error('Error resizing photo');
}
};
const upload = multer({
storage,
fileFilter: multerFilter
}).single('image')
app.post('/upload',upload,resizePhoto, (req, res) => {
if (!req.file) return next();
try{
let myFile = req.file.originalname.split(".")
const filname = myFile[0]
const fileType = myFile[myFile.length - 1]
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `dirname1/${filname}.${fileType}`,
Body: req.file.buffer
}
s3.upload(params, (error, data) => {
if(error){
res.status(500).send(error);
}
console.log(data);
console.log(data.Key);
console.log(data.Location);
res.status(200).send(data);
});
}catch(err){
console.log(err);
}
});
app.delete('/delete/:id', (req, res) => {
console.log(`Deleting file: ${req.params.id}...`);
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `dirname1/${req.params.id}`,
}
s3.deleteObject(params, (error, data) => {
if(error){
console.log(`AWS error: ${error}`);
res.status(500).send(error)
}
console.log(`AWS deleted file successfully`);
res.status(204).send(data);
});
});
app.listen(port, () => {
console.log(`Server is running at port: ${port}`)
})
@lcolsant
Copy link
Author

Added the following functionality:

-deleteObject route for removing objects from S3
-fileFilter for preventing non-image objects from being uploaded
-resizePhoto function for resizing and adjusting image quality (using Sharp library)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment