Table of Content
Image upload using multer in node js
Last modified: May 08, 2022- In the multer.diskStorage, we set the final destination path and filename
- In the multerFilter, we filter the type of files that can be uploaded
const db = require('../db/models/index');
const multer = require("multer");
const Movie = db.movie;
const Op = db.Sequelize.Op;
const path = require("path");
var fs = require('fs');
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, '/Users/reshamkafle/Desktop')
},
filename: (req, file, cb) => {
const ext = file.mimetype.split("/")[1];
cb(null, `/${file.fieldname}-${Date.now()}.${ext}`);
},
});
const multerFilter = (req, file, cb) => {
var ext = path.extname(file.originalname);
if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
cb(new Error('Only images are allowed'))
}
cb(null, true)
};
const uploadFile = multer({
storage: multerStorage,
limits: 3 * 1024 * 1024, //max 3MB file upload
fileFilter: multerFilter,
});
module.exports = function(app) {
app.post("/api/movie/upload" , uploadFile.single('uploadfile'), async function(request, response){
try {
await Movie.create({
title: request.body.title,
imageurl: request.file.filename,
videourl: request.body.videourl
})
.then(msg=>{
response.send({ message: "Movie is uploaded successfully!" });
});
} catch (error) {
response.status(500).send({ message: error.message });
}
});
}