Arthur Le Calvez
Arthur Le Calvez

Reputation: 433

How to handle errors with multer-s3

I am using multer-s3 to upload files to was S3. When i upload a file it all works fine and I have never had an error, however most tutorials do not mention anything about how to handle a case where there may be an issue with uploading files.

My upload is as follows

var upload = multer({
    storage: multerS3({
       s3: s3,
       bucket: 'my bucket',
       key: function (req, file, cb) {
          console.log(file);
          cb(null, file.originalname);
       }
    })
});

And i call it from the

app.post('/File/Add' , storage_functions.upload.single('file'), function (req, res) {
    console.log('file uploaded')

});

does multers3 provide some kind of response on upload. This would be useful to access errors but would also be useful if the response contained the file path in s3.

Upvotes: 0

Views: 4095

Answers (2)

MertStack
MertStack

Reputation: 51

This is what i did for handling errors: I have created a file s3.js, which includes multer-s3 configuration and error handler

import S3 from 'aws-sdk/clients/s3.js'
import multer from 'multer'
import multerS3 from 'multer-s3'
import dotenv from 'dotenv'

dotenv.config()

const region = process.env.S3_REGION

const s3 = new S3({
    region
})

// upload to S3 storage
export const uploadFiles = (req, res, next) => {

    const upload = multer({
        limits: { files: 6 }, 
        storage: multerS3({
            s3: s3,
            bucket: process.env.S3_BUCKET_NAME,
            metadata: function(req, file, cb) {
                cb(null, { fieldName: file.fieldname })
            },
            key: function(req, file, cb) {
                cb(null, `images/users/${ req.userId }/products/${ req.body.name }/${ new Date().toISOString() }-${ file.originalname }`)
            },
        })
    }).array('photos', 6)

    // Custom error handling for multer
    upload(req, res, (error) => {
        if (error instanceof multer.MulterError) 
            return res.status(400).json({ 
                message: 'Upload unsuccessful', 
                errorMessage: error.message,
                errorCode: error.code
            })
        
        if (error) 
            return res.status(500).json({
                message: 'Error occured',
                errorMessage: error.message
            })
        console.log('Upload successful.')
        next()
    })
}

You can now use this on the route that you want to upload files to.

import express from 'express'
import { uploadFiles } from '../config/s3.js'

const router = express.Router()

router.post('/upload', uploadFiles, async(req, res) => {
  console.log(req.files)
})

export default router

Because I set the file limit to 6 I will get the following response when I try to send more than 6 files.

multer-s3 number of file limit exceeded

Upvotes: 2

Jake Noh
Jake Noh

Reputation: 216

You can add callback function to handle errors.

const upload = storage_functions.upload.single('file');
app.post('/File/Add', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            // your error handling goes here
        }
    });
});

To find more details, multer documentation

Upvotes: 2

Related Questions