Express File Upload Middleware Multer detailed

Source: Internet
Author: User

Express does not handle the data in the HTTP request body by default, and it can use Body-parser middleware for normal request body (JSON, Binary, string) data. File uploads (Multipart/form-data requests) can be based on request flow processing, or you can use the formidable module or the Multer middleware.

1. Multer Middleware

Multer is an official express launch of the Node.jsmultipart/form-data middleware for requesting data processing.

It is built on busboy to efficiently process file uploads, but does not handle user requests outside of Multipart/form-data.

2. Installation

NPM Install Multer--save
3. Use

Multer After parsing the request body, a body object and a file or files object are added to the requests object (using the Files object when uploading multiple files). Where the Body object contains the text field (if any) in the submitted form, and the file (or files) object contains files uploaded through the form.

The basic usage examples are as follows:

var express = require (' Express ')
var multer = require (' Multer ')
var upload = Multer ({dest: ' uploads/'})
var app = Express ()
App.post ('/profile ', Upload.single (' Avatar '), function (req, res, next) {
Req.file is ' avatar ' file
The Req.body object is the text field (if any) that is submitted in the form
})
App.post ('/photos/upload ', Upload.array (' photos ', '), function (req, res, next) {
Req.files is an array of ' photos ' files
The Req.body object is the text field (if any) that is submitted in the form
})
var cpupload = 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), the name of the file is its key, and the file array is the value of key
//
Such as:
req.files[' Avatar '][0], File
req.files[' gallery '), Array
//
The Req.body object is the text field (if any) that is submitted in the form
})

In use, if you only need to work with text fields in the multipart form, you can use the. single (),. Array (), or field () methods in Multer.

For example, you can use the. Array () method as follows:

var express = require (' Express ')
var app = Express ()
var multer = require (' Multer ')
var upload = Multer ()
App.post ('/profile ', Upload.array (), function (req, res, next) {
Contains text fields in Req.body
})
4. Multer's API
4.1 File objects

Multer after parsing the upload file, it is saved as an object containing the following fields:

FieldName-file name of the form submission (the Name property of the input control)
Originalname-The original name of the file in the user device
Encoding-Encoding type of file
MimeType-MIME type of file
Size-Sizes of files
Destination-Save directory for files (diskstorage)
FileName-Name of the file in destination (diskstorage)
Path-the full path to the uploaded file (diskstorage)

Buffer-Buffer for file object (memorystorage)

4.2 Methods

Multer (OPTs)-Create object

After referencing the Multer module, we get to a top-level method. This method is a factory function that can be used to create a Multer object. It accepts an option object, and the most basic option is dest, which tells the Multer where the file is stored. If this option is omitted, the file is saved in memory and is never written to the hard disk.

By default, Multer will re-command the file to avoid name collisions. Rename functions, which can be customized as needed.

The Multer option object can contain the following values:

Dest or storage-file storage location
FileFilter-function to control the types of files that can be uploaded
Limits-Upload data limit (file size)

In a typical Web application, only the dest option needs to be set. Examples of use are:

var upload = Multer ({dest: ' uploads/'})

If you need more control over the upload file, you can use storage instead of Dest,multer to switch the storage engine from diskstorage (hard disk storage) to Memorystorage (memory storage).

After creating the Multer object, we can use the following instance to receive the uploaded file:

. single (fieldname)-Individual file uploads

Receive an upload file named FieldName, the uploaded file will be saved in Req.file.

. Array (fieldname[, MaxCount])-Multiple file uploads

Receives an array of multiple uploaded files named fieldname. The optional parameter Maxcount represents the number of acceptable files, and an error is thrown when the number of uploaded files exceeds the data specified by this parameter. The file array is saved in the req.files.

. Fields-Multiple file uploads

Receives multiple upload files specified through fields. The file array object is saved in the req.files.

Fields is an array of objects containing the name and Maxcount two properties:

[
{name: ' Avatar ', maxcount:1},
{Name: ' gallery ', maxcount:8}
]

. None ()-only text fields are resolved

Only text fields are parsed. A ' limit_unexpected_file ' error is triggered if there are any upload files in the request. This method is similar to Upload.fields ([]).

. any ()-Receive All Files

Receives all the files in the request. An array of uploaded files is saved in the req.files.

4.3 option parameters

Storage-Storage Engine

This option has the following two optional options:

Diskstorage-Hard disk storage
Memorystorage-Memory storage

. Diskstorage (obj) and hard disk storage

The hard disk storage engine provides full control over the storage of files to disk:

var storage = Multer.diskstorage ({
Destination:function (req, file, CB) {
CB (NULL, '/tmp/my-uploads ')
},
Filename:function (req, file, CB) {
CB (NULL, File.fieldname + '-' + Date.now ())
}
})
var upload = Multer ({storage:storage})

The. Diskstorage () method provides the file Store location CONTROL permission, which receives an object parameter that contains two destination and filename two properties.

Destination is used to set the storage directory for a file, which can be a function or a string. If this parameter is not provided, the system's TEMP directory will be used.

FileName is used to set the file name. If this argument is not provided, a random string is used and the file name does not contain an extension.

. Memorystorage () and memory storage

The memory storage engine saves the file in memory in the form of buffer. The method does not have any parameters:

var storage = Multer.memorystorage ()
var upload = Multer ({storage:storage})

Limits-File size

This option is used to set the file size, and Multer will pass the object to busboy. The following optional values can be included in the Limits object:

Fieldnamesize-The maximum size of the field name. Default value: bytes
FieldSize-The maximum size of the field value. Default value: 1MB
field-the maximum number of non-file fields. Default value: Infinity
Filesize-multipart the maximum size of a file in a form. Default value: Infinity
Files-multipart the maximum number of files in the form. Default value: Infinity
Parts-multipart the maximum number of components (fields+files) in the form. Default value: Infinity

Headerpairs-Default value: 2000

FileFilter-File filtering

The filefilter is used to control which files are acceptable and which are to be rejected. Use the following form:

function FileFilter (req, file, CB) {
Need to call callback function ' CB ',
And a Boolean value is passed in the second argument to indicate whether the file is acceptable
If you want to reject the file, the upload will pass ' false '. Such as:
CB (NULL, FALSE)
If you accept the upload file, pass in ' true '. Such as:
CB (NULL, TRUE)
After an error, you can pass in an error in the first parameter:
CB (New Error (' I don\ ' t has a clue! '))
}

Express File Upload Middleware Multer detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.