Objective
Express does not handle the data in the HTTP request body by default, and can use Body-parser middleware for the normal request body (JSON, Binary, string) data. File uploads (Multipart/form-data requests) can be processed based on request flow, or formidable modules or multer middleware can be used.
1. Multer Middleware
The Multer is an official express, a middleware for Node.jsmultipart/form-data request data processing.
It is built on busboy and can efficiently process file uploads, but does not deal with user requests outside of Multipart/form-data.
2. Installation
3. Use
After parsing the multer, a body object and a file or files object are added to the Request 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 that are uploaded by the form.
The basic use 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 ' text The part
//Req.body object is the text field (if any) that is submitted in the form (if any)
})
app.post ('/photos/upload ', Upload.array (' photos ',), function ( Req, res, next) {
//req.files is the ' photos ' file array
//Req.body object is the text field submitted in the form (if any)
})
var cpupload = Upload . Fields ([{name: ' Avatar ', maxcount:1}, {name: ' gallery ', Maxcount:8}])
app.post ('/cool-profile ', Cpupload, func tion (req, res, next) {
//Req.files is an object (String-> array), the file's field name is its key, and the file array is the value of the key
//
////////
eq.files[' Avatar '][0]-> file
//req.files[' gallery ']-> Array////
Req.body object is the text field submitted in the form (if any )
})
In use, if you only need to work with text fields in multipart forms, you can use the .single()
, or methods in Multer .array()
fields()
.
For example, you can use this .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) {
//Req.body contains text fields
})
4. API for Multer
4.1 File objects
Multer after parsing the upload file, it is saved as an object that contains the following fields:
FieldName-file name of the form submission (Name property of the input control)
Originalname-The original name of the file in the user's device
Encoding-Encoding type of file
MimeType-MIME type of file
Size-Sizes of files
Destination-Save directory for files (diskstorage)
FileName-the name of the file in destination (diskstorage)
Path-full path to upload file (diskstorage)
Buffer-Buffer for file object (memorystorage)
4.2 Method
multer(opts)
-Create objects
After referencing the Multer module, we will get a top-level method. This method is a factory function that you can use to create a Multer object. It accepts an option object, and the most basic option is dest, which tells Multer where the file is stored. If this option is omitted, the file is saved in memory and will never be written to the hard disk.
By default, multer commands the file to avoid name collisions. Renaming functions, you can customize them as needed.
The Multer option object can contain the following values:
Dest or storage-file storage location
FileFilter-functions, controlling the types of files that can be uploaded
Limits-Upload data restrictions (file size)
In a typical Web application, only the dest option needs to be set. Use the example below:
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)
-Single File Upload
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 upload files named fieldname. An optional parameter maxcount represents an acceptable number of files, and an error is thrown after the number of uploaded files exceeds the data specified by the parameter. The file array is saved in the req.files.
.fields(fields)
-Multiple file uploads
Receives multiple upload files specified by 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()
-Resolve text fields only
Resolves only text fields. If there are any uploaded files in the request, a ' limit_unexpected_file ' error will be triggered. This method is similar to Upload.fields ([]).
.any()
-Receive All Files
Receives all files in the request. An array of uploaded files will be 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)
With 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 ')
},< C10/>filename:function (req, file, CB) {
CB (NULL, File.fieldname + '-' + Date.now ()
}
})
var upload = Multer ({storage:storage})
.diskStorage()
method provides the file storage location Control permission, which receives an object parameter that contains two destination and filename two properties.
Destination is used to set up a file's storage directory, which can be a function or string. If this parameter is not provided, the system's temporary directory is used.
FileName is used to set the filename. If this argument is not supplied, a random string is used and the file name does not contain an extension.
.memoryStorage()
With memory storage
The memory storage engine saves the file in memory in the form of a 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 this object to the busboy. The Limits object can contain the following optional values:
Fieldnamesize-The maximum size of the field name. Default value: bytes
FieldSize-The maximum size of the field value. Default value: 1MB
Fields-the maximum number of non-file fields. Default value: Infinity
Filesize-multipart the maximum size of the 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
FileFilter is used to control which files are acceptable and which are to be rejected. The use form is as follows:
function FileFilter (req, file, CB) {
//need to invoke the callback function ' CB ',
//And pass a Boolean value in the second argument to indicate whether the file is acceptable
////If you want to reject the file, upload the ' False '. such as:
CB (NULL, FALSE)
//If the upload file is accepted, pass ' true '. such as:
CB (NULL, TRUE)
//error, you can pass an error in the first parameter:
CB (New Error (' I don\ ' t have a clue! ')
}
Summarize
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.