Multer is a node.js middleware for handlingmultipart/form-data
,which is primarily used for uploading files. It is written
on top ofbusboyfor maximum efficiency.
NOTE:Multer will not process any form which is not multipart (multipart/form-data
).
This README is also available in other languages:
- العربية(Arabic)
- Español(Spanish)
- Giản thể tiếng Trung(Chinese)
- 한국어(Korean)
- Русский язык(Russian)
- Việt Nam(Vietnam)
- Português(Portuguese Brazil)
- Français(French)
- O'zbek tili(Uzbek)
$ npm install --save multer
Multer adds abody
object and afile
orfiles
object to therequest
object. Thebody
object contains the values of the text fields of the form, thefile
orfiles
object contains the files uploaded via the form.
Basic usage example:
Don't forget theenctype= "multipart/form-data"
in your form.
<formaction= "/profile"method= "post"enctype= "multipart/form-data">
<inputtype= "file"name= "avatar"/>
</form>
constexpress=require('express')
constmulter=require('multer')
constupload=multer({dest:'uploads/'})
constapp=express()
app.post('/profile',upload.single('avatar'),function(req,res,next){
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload',upload.array('photos',12),function(req,res,next){
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
constcpUpload=upload.fields([{name:'avatar',maxCount:1},{name:'gallery',maxCount:8}])
app.post('/cool-profile',cpUpload,function(req,res,next){
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})
In case you need to handle a text-only multipart form, you should use the.none()
method:
constexpress=require('express')
constapp=express()
constmulter=require('multer')
constupload=multer()
app.post('/profile',upload.none(),function(req,res,next){
// req.body contains the text fields
})
Here's an example on how multer is used an HTML form. Take special note of theenctype= "multipart/form-data"
andname= "uploaded_file"
fields:
<formaction= "/stats"enctype= "multipart/form-data"method= "post">
<divclass= "form-group">
<inputtype= "file"class= "form-control-file"name= "uploaded_file">
<inputtype= "text"class= "form-control"placeholder= "Number of speakers"name= "nspeakers">
<inputtype= "submit"value= "Get me the stats!"class= "btn btn-default">
</div>
</form>
Then in your javascript file you would add these lines to access both the file and the body. It is important that you use thename
field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail:
constmulter=require('multer')
constupload=multer({dest:'./public/data/uploads/'})
app.post('/stats',upload.single('uploaded_file'),function(req,res){
// req.file is the name of your file in the form above, here 'uploaded_file'
// req.body will hold the text fields, if there were any
console.log(req.file,req.body)
});
Each file contains the following information:
Key | Description | Note |
---|---|---|
fieldname |
Field name specified in the form | |
originalname |
Name of the file on the user's computer | |
encoding |
Encoding type of the file | |
mimetype |
Mime type of the file | |
size |
Size of the file in bytes | |
destination |
The folder to which the file has been saved | DiskStorage |
filename |
The name of the file within thedestination |
DiskStorage |
path |
The full path to the uploaded file | DiskStorage |
buffer |
ABuffer of the entire file |
MemoryStorage |
Multer accepts an options object, the most basic of which is thedest
property, which tells Multer where to upload the files. In case you omit the
options object, the files will be kept in memory and never written to disk.
By default, Multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs.
The following are the options that can be passed to Multer.
Key | Description |
---|---|
dest orstorage |
Where to store the files |
fileFilter |
Function to control which files are accepted |
limits |
Limits of the uploaded data |
preservePath |
Keep the full path of files instead of just the base name |
In an average web app, onlydest
might be required, and configured as shown in
the following example.
constupload=multer({dest:'uploads/'})
If you want more control over your uploads, you'll want to use thestorage
option instead ofdest
.Multer ships with storage enginesDiskStorage
andMemoryStorage
;More engines are available from third parties.
Accept a single file with the namefieldname
.The single file will be stored
inreq.file
.
Accept an array of files, all with the namefieldname
.Optionally error out if
more thanmaxCount
files are uploaded. The array of files will be stored in
req.files
.
Accept a mix of files, specified byfields
.An object with arrays of files
will be stored inreq.files
.
fields
should be an array of objects withname
and optionally amaxCount
.
Example:
[
{name:'avatar',maxCount:1},
{name:'gallery',maxCount:8}
]
Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.
Accepts all files that comes over the wire. An array of files will be stored in
req.files
.
WARNING:Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files.
The disk storage engine gives you full control on storing files to disk.
conststorage=multer.diskStorage({
destination:function(req,file,cb){
cb(null,'/tmp/my-uploads')
},
filename:function(req,file,cb){
constuniqueSuffix=Date.now()+'-'+Math.round(Math.random()*1E9)
cb(null,file.fieldname+'-'+uniqueSuffix)
}
})
constupload=multer({storage:storage})
There are two options available,destination
andfilename
.They are both
functions that determine where the file should be stored.
destination
is used to determine within which folder the uploaded files should
be stored. This can also be given as astring
(e.g.'/tmp/uploads'
). If no
destination
is given, the operating system's default directory for temporary
files is used.
Note:You are responsible for creating the directory when providing
destination
as a function. When passing a string, multer will make sure that
the directory is created for you.
filename
is used to determine what the file should be named inside the folder.
If nofilename
is given, each file will be given a random name that doesn't
include any file extension.
Note:Multer will not append any file extension for you, your function should return a filename complete with an file extension.
Each function gets passed both the request (req
) and some information about
the file (file
) to aid with the decision.
Note thatreq.body
might not have been fully populated yet. It depends on the
order that the client transmits fields and files to the server.
For understanding the calling convention used in the callback (needing to pass null as the first param), refer to Node.js error handling
The memory storage engine stores the files in memory asBuffer
objects. It
doesn't have any options.
conststorage=multer.memoryStorage()
constupload=multer({storage:storage})
When using memory storage, the file info will contain a field called
buffer
that contains the entire file.
WARNING:Uploading very large files, or relatively small files in large numbers very quickly, can cause your application to run out of memory when memory storage is used.
An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found onbusboy's page.
The following integer values are available:
Key | Description | Default |
---|---|---|
fieldNameSize |
Max field name size | 100 bytes |
fieldSize |
Max field value size (in bytes) | 1MB |
fields |
Max number of non-file fields | Infinity |
fileSize |
For multipart forms, the max file size (in bytes) | Infinity |
files |
For multipart forms, the max number of file fields | Infinity |
parts |
For multipart forms, the max number of parts (fields + files) | Infinity |
headerPairs |
For multipart forms, the max number of header key=>value pairs to parse | 2000 |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:
functionfileFilter(req,file,cb){
// The function should call `cb` with a boolean
// to indicate if the file should be accepted
// To reject this file pass `false`, like so:
cb(null,false)
// To accept the file pass `true`, like so:
cb(null,true)
// You can always pass an error if something goes wrong:
cb(newError('I don\'t have a clue!'))
}
When encountering an error, Multer will delegate the error to Express. You can display a nice error page usingthe standard express way.
If you want to catch errors specifically from Multer, you can call the
middleware function by yourself. Also, if you want to catch onlythe Multer errors,you can use theMulterError
class that is attached to themulter
object itself (e.g.err instanceof multer.MulterError
).
constmulter=require('multer')
constupload=multer().single('avatar')
app.post('/profile',function(req,res){
upload(req,res,function(err){
if(errinstanceofmulter.MulterError){
// A Multer error occurred when uploading.
}elseif(err){
// An unknown error occurred when uploading.
}
// Everything went fine.
})
})
For information on how to build your own storage engine, seeMulter Storage Engine.