What is multer module in node.js?
why use multer module ?
Multer module is used for file uploading in node.Js. there are various module available in node.Js for file uploading.
Multer is a middleware which is used for handling file uploading(multipart/form-data).
There are two ways to upload forms with multipart/form-data encoding.
using the enctype attribute: (enctype='multipart/form-data')
using the FormData API.
The FormData API allows us to build a multipart/form-data form with key-value pairs that can be sent to the server.
const frmd = new FormData()
frmd.append('name', "Dillion")
frmd.append('image', <a file>)
Multer does the work of body-parser by attaching the values of text fields in the req.body object. Multer also creates a new object for multiple files, either req.file or req.files, which holds information about those files.
How to install multer?
File Name :
npm install multer
############## OR ##############
npm install --save multer
Check Version of multer
File Name :
npm version multer
Requiring module:
File Name :
var multer = require('multer');
Multer basically adds a file object or files object and a body object to the request object.
The file/files object contains all the files which are uploaded through the form and all the values of the text fields of the form are contained in the body object.
Html Form for File uploading :-
For uploading file You have to must declare three main attributes within the form tag.
File Name :
action=/upload_file" :- when you submit the form It will redirect to /upload_file action through the POST method.
method="POST" :- post method is user to send form information on action page.
enctype="multipart/form-data" :- enctype handles file uploading request.
<form action="/upload_file" method="POST" enctype="multipart/form-data">
input field :-
html input tag containg mainly three attributes for file uploading.
File Name :
type="file" – input type file is used to creates a browse Button to select any files from your device.
name="myfile" – name is used to access file information.
multiple – multiple is optional. when you want to upload multiple file then write multiple. It allows us to select multiple files/images at a time
<input type="file" name="myfile" multiple>
Example :- Html form for file upload in node.js
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="/upload_file" method="POST" enctype="multipart/form-data">
<label>Store Files</label><br><br>
<p><%=(typeof alertMsg!='undefined')? alertMsg:''%></p>
<input type="file" name="myfile" multiple>
<button type="submit">Upload</button>
</form>
</body>
</html>
Previous
Next