1 minute read

Upload a single file to AWS S3 using Multer

💭 How to upload files to AWS S3?

  • 🧐 Node.js use multer as a middleware to upload files to S3 bucket in AWS

    1. Create a AWS S3 Bucket

    Follow steps in the link below: How to create a AWS S3 Bucket

    2. Make a AWS IAM User

Follow steps in the link below: How to create IAM User
image

3. Use multer to upload files to AWS

📋 < Ubuntu Terminal >

npm install aws-sdk

Install the aws-sdk

📋 < s3.json >

{  
  "accessKeyId": "Your access key ID",  
  "secretAccessKey": "Your secret access key",  
  "region": "ap-northeast-2" 
}

Create s3.json file and type your IAM access key ID, secret access key. ❗ This file must be added to .gitignore file to secure your AWS account

📋 < multer.js >

const multer = require('multer');  
const multerS3 = require('multer-s3');  
const aws = require('aws-sdk');  
aws.config.loadFromPath(__dirname + '/s3.json');  
  
const s3 = new aws.S3();  

// filter file type
const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb(new Error("Invalid mime type, only JPEG and PNG"), false);
  }
};

// upload file
const upload_image = multer({  
    storage: multerS3({  
        s3: s3,  
  bucket: 'Your bucket name',  
  key: function (req, file, cb) {  
            cb(null, 'directory path'+ Date.now() + '.' + file.originalname); //use Date.now() for unique file keys  
  }  
    })  
});  
  
module.exports = upload_image;

Import multer to upload file

📋 < routes/users.js >

const upload = require('../modules/multer');

router.patch('/URI', upload.single('profile_image'), UserController.updateProfileImage);
Code How it works
.single(‘field name’) upload single file
.array(‘field name’) upload multiple files
.fields([{name: ‘field name’, maxCount: ‘maximum number of files’}, {name: ‘field name’, maxCount: ‘maximum number of files’]) upload mutiple files from different fields


📋 < controllers/userController.js >

updateProfileImage: async (req, res) => {  
  
  // Validation  
  if (req.file === undefined) {    
        return res.send('profile_image is null');  
  } else {  
		// get file location
        var image = req.file.location;  
        return res.send(image);  
  }   
}

Categories:

Updated: