Multer and expressmulter for uploading Express files
Multer for uploading Express files
Multer is a nodejs middleware used to process multipart/form-data submitted over http, that is, file upload. It is developed based on busboy.
In my opinion, Multer is the most elegant to use in many upload middleware and can meet most of the upload requirements. APIs are relatively intuitive and simple.
Install
1 |
npm install multer --save |
Basic usage
12345 |
var express = require('express')var multer = require('multer')var app = express()app.use(multer({ dest: './uploads/'})) |
1234 |
router.use(function(req,res,next){console.log(req.files); //JSON Objectnext();}); |
From the code above, we can see that multer passed in app. use as a middleware. When an upload request arrives, express intercepts this request and completes the upload operation through the multer component. The configuration object is input in the multer initialization method. We can configure custom parameters in the parameter, such as "file size limit" and "file quantity limit.
You can not only add restrictions, but also upload and register events. For example:
1234567891011 |
// OnFileUploadStart is triggered when the upload starts: function (file) {console. log ("upload start");} // onFileUploadComplete: function (file) {console. log ("upload complete ");}...... |
In the actions that actually accept the upload, we obtain the basic information of the file through the files in req. The information is in JSON format and the common information is as follows.
Originalname-original file name
Path-path for storing uploaded files
Size-File size
For more details about attributes and configurations, see the Multer Github homepage.
Multer
Author: foreverpx
Original article: Multer of Express File Upload