DEV Community

Cover image for File Upload With Multer
Bibek Dhami
Bibek Dhami

Posted on • Originally published at bvek.hashnode.dev

File Upload With Multer

Multer is a library for handling file upload with form/multipart-formdata.

Step

  1. Installing Package
  2. Multer fileUpload and file type validation
  3. Initialize upload variable
  4. Insert image path in database
  5. Retrieve Uploaded Image

Installing Package

npm install multer
npm install path
Enter fullscreen mode Exit fullscreen mode

require both install packages at top of your code file.

const multer = require('multer')
const path = require('path')
Enter fullscreen mode Exit fullscreen mode

*2. Multer File Upload and file type validation *

let's create a function which will store image.
multer disk storage stores the file in the disk. multer will remove the file extension so that we can add the file extension with file.orginalname.

Date.now() to give a unique name for each file.

file.fieldname is a value that we specify in our form value.

Note: If file.orginalname is not specified multer will assign a random file value for each file without extension.

const storage = multer.diskStorage({
     Destination:"upload/profile",
     Filename(req,fiel,cb)=>{
     cb(null,file.fieldname+"-"+Date.now()+file.originalname)
}
})
Enter fullscreen mode Exit fullscreen mode

Specify the directory in which you want to store your files. No need to manually create your directory manually multer will take care of that for you.

now let's add some file validation so that we can restrict users to only upload the filetype we defined.

const fileFilter =(req,file,callback)=>{
let ext = apth.extname(file.originalname)
if(ext !=='png' && ext !=='jpg' && ext !=='jpeg'){
return callback(new Error('Only png, ext and jpeg fileType are allowed))
}
Callback(null,true)
}
Enter fullscreen mode Exit fullscreen mode

3. Initialize Upload variable

let upload = multer({
storage:storage,
fileFilter:fileFilter
})
Enter fullscreen mode Exit fullscreen mode

For file upload

"module.exports.imageName = upload.single("image")"

4. Insert ImagePath in DataBase

Now let's insert Image Path and Image Name in the Database. We will use the above multer upload function as middleware for our function. Multer provides an API through which we can retrieve the details of the file we have uploaded. Some of them are;
file. filename will give us upload filename, mimetype will give us file extension.

module.exports.profilePic = async(req,res)=>{
    let  insertObject ={};
    console.log(req.file)    
     insertObject.imageName = req.file.filename;
    insertObject.type = req.file.mimetype;
    insertObject.path = req.file.path
    insertObject.personId = req.params.personId;
     console.log("this is inside function",insertObject)
    await knex("tbl_profile").insert(insertObject).then((doc)=>{
        res.json({status:"success",message:"success"});
    }).catch((err)=>{
        console.log("THis is err",err)
        res.json({status:"error",message:"error"})
    })
}

Enter fullscreen mode Exit fullscreen mode

create a router for inserting an image and use the image name function as middleware

router.post("/profile/:personId",imageName,profilePic)
Enter fullscreen mode Exit fullscreen mode

test image upload in postman

postManUpload.PNG
5. Reterive Image

As the image has been added now let's retrieve the image by person Id.
For that, we need to first select the image path for a given personId and then join it with a path to retrieve the image.

module.exports.pic = async(req,res)=>{
    const personId = req.params.personId;
    await knex("tbl_profile").select('path').where('personId',personId).then((doc)=>{
  let filePath = doc[0]
  let  imageUrl = filePath.path
  const dirname = path.resolve();
  const fileUrl = path.join(dirname,imageUrl);
        res.sendFile(fileUrl)
    }).catch((err)=>{
        console.log("This is an error",err)
        res.json({status:"error",message:"error reterving messsage"})
    })
}
Enter fullscreen mode Exit fullscreen mode
router.get("/profile/:personId",pic)
Enter fullscreen mode Exit fullscreen mode

*Preview Image Using Postman *
reteriveImageUpload.PNG

SourceCode

Top comments (0)