Skip to content

Instantly share code, notes, and snippets.

@nyx-code
Last active November 25, 2022 20:50
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 21 You must be signed in to fork a gist
  • Save nyx-code/c1c07dc7830cd596c7a1b48d0dd5d15f to your computer and use it in GitHub Desktop.
Save nyx-code/c1c07dc7830cd596c7a1b48d0dd5d15f 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 AWS = require('aws-sdk')
const uuid = require('uuid/v4')
const app = express()
const port = 3000
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ID,
secretAccessKey: process.env.AWS_SECRET
})
const storage = multer.memoryStorage({
destination: function(req, file, callback) {
callback(null, '')
}
})
const upload = multer({storage}).single('image')
app.post('/upload',upload,(req, res) => {
let myFile = req.file.originalname.split(".")
const fileType = myFile[myFile.length - 1]
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `${uuid()}.${fileType}`,
Body: req.file.buffer
}
s3.upload(params, (error, data) => {
if(error){
res.status(500).send(error)
}
res.status(200).send(data)
})
})
app.listen(port, () => {
console.log(`Server is up at ${port}`)
})
@yashtibrewal
Copy link

yashtibrewal commented Dec 30, 2020

Thanks
btw I think we actually don't need to create memory storage or do we?
my code works with no params in multer , i.e const upload = multer().single('image')

@harshjoeyit
Copy link

I was getting error from aws-sdk,
the reason was using " " in .env file .
You should store AWS_ID, AWS_SECRET and AWS_BUCKET_NAME without " " around them.

@Dandarprox
Copy link

Just wanted to mention that the new recommended structure is this:

const s3 = new AWS.S3({
    credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    },
});

@shah21
Copy link

shah21 commented Mar 12, 2021

Error : expected 0 arguments, but got 1.ts(2554) when usgin multer.memmoryStorage({....}) why

@HappyDevCompany
Copy link

thanks bro for sharing beautifull and simple code example 🙏

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