multer based tutorial

When this document translation on October 3, 2016 multer version is 1.2.0, it may not be the latest! Translation errors may even exist! You may want to read the original English README  This document is for informational purposes only!

cloudberries 

Multer is a node.js middleware to handle  multipart/form-data the type of form data, which is mainly used to upload files. It is written in  busboy  on very efficient.

Note: Multer not process any non-  multipart/form-data type form data.

installation

$ npm install --save multer

use

Multer will add a  body subject and  file or  files objects to express the  request object. body Text fields contain forms of information objects, file or  files objects that contain information about an object file upload form.

Basic use:

var Express = the require ( 'Express' )
 var multer the require = ( 'multer' )
 var Upload = multer ({dest: 'uploads /' }) 

var App = Express () 

app.post ( '/ Profile', upload.single ( 'Avatar'), function (REQ, RES, Next) {
   // req.file `avatar` information file 
  // req.body having a text data field, if present, 
}) 

app.post ( '/ photos / Upload ', upload.array (' photos', 12 is), function (REQ, RES, Next) {
   // req.files `photos` information file array 
  // req.body having a text data field, if present, words 
}) 

var= upload.fields cpUpload ([{name: 'Avatar', maxCount:. 1}, {name: 'Gallery', maxCount:. 8 }]) 
app.post ( '/ Cool-Profile', cpUpload, function (REQ, RES , Next) {
   // req.files is an object (String -> array) key is the file name, the file is an array of values 
  //
   // example: 
  //   req.files [ 'Avatar'] [0] -> file 
  / /   req.files [ 'Gallery'] -> the Array 
  //
   // req.body having a text data field, if present, 
})

 

If you only need to deal with a form text field, you should use  .none():
was Out = require ( 'Out' )
 was app = Out ()
 was cloudberry = require ( 'cloudberry' )
 was upload = cloudberry () 

app.post ( '/ profile', upload.none () function (req, res , next) {
   // req.body包含文本域 
})

API

File information

Each file has the following information:

Key Description Note
fieldname Field name specified by the form  
originalname Name of the file on the user's computer  
encoding file encoding  
mimetype MIME type of the file  
size File size (bytes units)  
destination save route DiskStorage
filename Saved in the  destination file name DiskStorage
path Uploaded the full path to the file DiskStorage
buffer A store the entire file Buffer MemoryStorage

multer(opts)

Multer options to accept a target, which is the most basic  dest attributes, which will tell Multer in which to save the file to upload. If you omit the options object, these files will be stored in memory and never written to disk.

To avoid naming conflicts, Multer will rename the file upload. The Rename function can be customized according to your needs.

The following are the options can be passed to Multer.

Key Description
dest or storage Where to store files
fileFilter File filters, which can be accepted file control
limits Limiting data uploads
preservePath Save the file that contains the full path to the file name

In general, the general web applications, only need to set  dest properties like this:

was uploaded = mullet ({dest: 'uploads /'})

 

If you want more control when uploading, you can use the  storage option to substitute  dest. Having Multer  DiskStorage and  MemoryStorage two storage engines; also can obtain more usable engine from a third party.

.single(fieldname)

To accept a  fieldname file named. This information is stored in the file  req.file.

.array(fieldname[, maxCount])

To accept a  fieldname array named file. It can be configured  maxCount to limit the maximum number of uploads. Information stored in these files  req.files.

.fields(fields)

Accept the specified  fields mix file. Information stored in these files  req.files.

fields Should be an array of objects, you should have  name and optional  maxCount attributes.

Example:

[
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
]

 

.none()

Only accept text field. If any files uploaded to this mode, "LIMIT_UNEXPECTED_FILE" error will occur. This is  upload.fields([]) the same effect.

.any()

Accept all uploaded files. An array of files will be saved  req.files.

Warning: Make sure you always deal with the user's files to upload. Never will multer as the global middleware used because a malicious user can upload files to a route that you did not anticipate, should only be used on the route you need to process the uploaded file.

storage

Disk storage engine ( DiskStorage)

Disk storage engine that lets you control the file is stored.

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 })

Two options are available, destination and  filename. They are used to determine the function file storage location.

destination It is used to determine the uploaded files should be stored in which folder. It may also provide a  string (e.g.  '/tmp/uploads'). If not set  destination, use the default operating system temporary folder.

Note: If you provide  destination a function, you need to be responsible for creating folders. When a string, multer will ensure that the folder you created.

filename Determine the file name in the folder to determine. If not set  filename, each file will be set to a random file name, and there is no extension.

Note: Multer does not add any extension for you, your program should return a full file name.

Each function is passed the request object ( req) and some information about the file ( file), help your decision.

Note  req.body may not completely filled, depending on the field and send files to clients to order servers.

Memory storage engine ( MemoryStorage)

Memory storage engine to store files in memory  Buffer objects, it does not have any options.

was storage = multer.memoryStorage ()
 was upload = cloudberry ({storage: storage})

 

When memory storage engine, the information file contains a  buffer field, which contains the entire data file.

Warning: When you use memory to store a small file, upload very large files, or very large, it will cause your application memory overflow.

limits

An object, some of the specified data size limit. Multer this object by using the busboy, detailed characterization can  busboy's page  to find.

The following can be used:

Key Description Default
fieldNameSize The maximum length of the field name 100 bytes
fieldSize The maximum value of the length field 1MB
fields The maximum number of non-file field unlimited
fileSize In the multipart form, the maximum document length (byte unit) unlimited
files In multipart forms, the maximum number of files unlimited
parts In the multipart form, the maximum number of transmissions part (fields + files) unlimited
headerPairs In the multipart form, set the maximum number of key-value pairs 2000

Setting limits can help protect your site against denial of service (DoS) attacks.

fileFilter

Set a function to control what files can be uploaded and what file should skip this function should look like this:

function fileFilter (REQ, File, cb) { 

  // This function should be called `cb` a boolean value 
  // indicate whether or not to accept the file 

  // reject the file, use` false`, like this: 
  cb ( null , false ) 

  // accept the file, use `true`, like this: 
  cb ( null , to true ) 

  // If you have questions, you can always send an error: 
  cb ( new new error ( 'the I Don \' t have have a CLUE ! ' )) 

}

 

Error handling mechanism

When an error is encountered, multer will send the error to express. You can use a good show error page ( Express standard mode ).

If you want to catch errors multer issued, you can call yourself a middleware program. If you want to capture  Multer error , you can use the  multer next object  MulterError class (that is  err instanceof multer.MulterError).

var multer the require = ( 'multer' )
 var Upload multer = (). SINGLE ( 'Avatar' ) 

app.post ( '/ Profile', function (REQ, RES) { 
  Upload (REQ, RES, function (ERR) {
     IF (ERR the instanceof multer.MulterError) {
       // error occurred 
    } the else  IF (ERR) {
       // an error occurred 
    } 

    // everything 
  }) 
})

 

Custom storage engine

If you want to build your own storage engines, see  here  .

License

WITH

Guess you like

Origin www.cnblogs.com/sexintercourse/p/11783741.html