To upload image in nodejs we need Multer middleware. Multer is a node.js middleware for handling
multipart/form-data
, which is primarily used for uploading files.Multer adds a
body
object and a file
or files
object to the request
object. The body
object contains the values of the text fields of the form, the file
or files
object contains the files uploaded via the form.Step I) In your router.js file:- define multer first
const multer = require('multer');
Step II) Define Storage using multer.diskStorage() function just like below:
const storage = multer.diskStorage({destination: "images",filename: (req, file, cb) => {cb(null, file.originalname)},})
Step III) Define your file extenstion (like jpg, png, jpeg) which are your requirements jsut like below:
const filefilter = (req, file, cb) => {if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {cb(null, true)} else {cb(null, false)}}
Step IV) Store the storage value and filefiletr value in upload using multer function just like below:-
const upload = multer({ storage: storage, fileFilter: filefilter });
Step V) Now define upload.single with image name as middleware in your post router just like below:-
router.post('/signup', upload.single('img'), async (req, res) => {const img = req.file.path;console.log(img)})
Step VI) Now add
enctype="multipart/form-data"
in your HTML form and also add file type i.e. file :-<form action="/signup" enctype="multipart/form-data" method="POST"><input type="file" name="img"><button type="submit" value="Upload Photo" onchange="handleInputs">Submit</button></form>
Step VII) Now finally test your route in postman, In postman select form-data in body and provide file name "img" & upload any image then heat request. Thank you So much!
0 Comments
Thank you for Comment