File Upload with Nodejs, Cloudinary, Multer - Part 2

File Upload with Nodejs, Cloudinary, Multer - Part 2

Continuation!!

What are we gonna do?

I explained about how to perform a simple image upload to cloudinary as cloud storage service with nodejs and express using multer.

You can read about it here

This is a continuation to that where we are going to discuss how to use fileFilter to filter the files and put a constraint on valid file extensions, setting up custom filename for files to be uploaded and also error handling of the same

Error Handling and fileFilter

Let's Jump direclty into code

const express= require('express');
const { MulterError } = require('multer');
const app=express()
const multer=require('multer')
const path=require('path')
const cloudinary=require('cloudinary').v2

const imageExtensions=['.jpeg','.jpg','.png']
//you can specify any image extensions you think are valid
//if you are trying to upload any other files other than images,it is explained further in the blog.

class ExtensionError extends Error{
    constructor(message,status){
        super()
        this.message=message;
        this.status=status
    }
}
cloudinary.config({
    cloud_name:"your_cloud_name",
    api_key:"your_api_key",
    api_secret:"your_api_secret"
})


//uploader corresponds to multer middleware

const uploader=multer({
    storage: multer.diskStorage({
        filename:(req,file,cb)=>{
            cb(null,file.fieldname+'_'+new Date().valueOf()+path.extname(file.originalname))

        }
    }), //say to multer to store the intermediate in diskstorage before uploading
    //filtering valid files based on extension
    fileFilter: (req,file,cb)=>{
        let ext=path.extname(file.originalname);
        if(!imageExtensions.includes(ext)){
            cb(new ExtensionError("Unsupported file extension",400),false)
        }
        cb(null,true)
    }
}).single('image') //this line of code is explained below in the article




app.post('/upload',uploader, async  (req,res)=>{
    const data= await cloudinary.uploader.upload(req.file.path,{
        folder:"folder_name_of_your_choice",
        use_filename:true
    })
    console.log(data)
    return res.send("Uploaded!!")
})

//error handling middleware
app.use((err,req,res,next)=>{
    res.status(err.status).json({"message":err.message})
})

app.listen(3000,()=>{
    console.log('Listening on post 3000......')
})

Note: If you add '.txt' in the valid extensions array and try to upload a text file, you won't succeed because any file other than media files are to be uploaded to cloudinary as raw files and the process for that is easy.

The only change in the code will be in the segment where we upload the file to cloudinary.

We specify resource_type as 'auto' to let cloudinary automatically determine the type as which the file to be uploaded

app.post('/upload',uploader, async  (req,res)=>{
    const data= await cloudinary.uploader.upload(req.file.path,{
        folder:"blogsfolder",
        use_filename:true,
        resource_type:'auto'
    })
    console.log(data)
    return res.send("Uploaded!!")
})

Conclusion

So, we have seen how to specify fileFilter and handle errors.

Happy Development!

Feedback is appreciated.