UNPKG

10.3 kBMarkdownView Raw
1# Multer [![Build Status](https://travis-ci.org/expressjs/multer.svg?branch=master)](https://travis-ci.org/expressjs/multer) [![NPM version](https://badge.fury.io/js/multer.svg)](https://badge.fury.io/js/multer) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
2
3Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written
4on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency.
5
6**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`).
7
8## Translations
9
10This README is also available in other languages:
11
12- [简体中文](https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md) (Chinese)
13- [한국어](https://github.com/expressjs/multer/blob/master/doc/README-ko.md) (Korean)
14- [Русский язык](https://github.com/expressjs/multer/blob/master/doc/README-ru.md) (Russian)
15
16## Installation
17
18```sh
19$ npm install --save multer
20```
21
22## Usage
23
24Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form.
25
26Basic usage example:
27
28Don't forget the `enctype="multipart/form-data"` in your form.
29
30```html
31<form action="/profile" method="post" enctype="multipart/form-data">
32 <input type="file" name="avatar" />
33</form>
34```
35
36```javascript
37var express = require('express')
38var multer = require('multer')
39var upload = multer({ dest: 'uploads/' })
40
41var app = express()
42
43app.post('/profile', upload.single('avatar'), function (req, res, next) {
44 // req.file is the `avatar` file
45 // req.body will hold the text fields, if there were any
46})
47
48app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
49 // req.files is array of `photos` files
50 // req.body will contain the text fields, if there were any
51})
52
53var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
54app.post('/cool-profile', cpUpload, function (req, res, next) {
55 // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
56 //
57 // e.g.
58 // req.files['avatar'][0] -> File
59 // req.files['gallery'] -> Array
60 //
61 // req.body will contain the text fields, if there were any
62})
63```
64
65In case you need to handle a text-only multipart form, you should use the `.none()` method:
66
67```javascript
68var express = require('express')
69var app = express()
70var multer = require('multer')
71var upload = multer()
72
73app.post('/profile', upload.none(), function (req, res, next) {
74 // req.body contains the text fields
75})
76```
77
78## API
79
80### File information
81
82Each file contains the following information:
83
84Key | Description | Note
85--- | --- | ---
86`fieldname` | Field name specified in the form |
87`originalname` | Name of the file on the user's computer |
88`encoding` | Encoding type of the file |
89`mimetype` | Mime type of the file |
90`size` | Size of the file in bytes |
91`destination` | The folder to which the file has been saved | `DiskStorage`
92`filename` | The name of the file within the `destination` | `DiskStorage`
93`path` | The full path to the uploaded file | `DiskStorage`
94`buffer` | A `Buffer` of the entire file | `MemoryStorage`
95
96### `multer(opts)`
97
98Multer accepts an options object, the most basic of which is the `dest`
99property, which tells Multer where to upload the files. In case you omit the
100options object, the files will be kept in memory and never written to disk.
101
102By default, Multer will rename the files so as to avoid naming conflicts. The
103renaming function can be customized according to your needs.
104
105The following are the options that can be passed to Multer.
106
107Key | Description
108--- | ---
109`dest` or `storage` | Where to store the files
110`fileFilter` | Function to control which files are accepted
111`limits` | Limits of the uploaded data
112`preservePath` | Keep the full path of files instead of just the base name
113
114In an average web app, only `dest` might be required, and configured as shown in
115the following example.
116
117```javascript
118var upload = multer({ dest: 'uploads/' })
119```
120
121If you want more control over your uploads, you'll want to use the `storage`
122option instead of `dest`. Multer ships with storage engines `DiskStorage`
123and `MemoryStorage`; More engines are available from third parties.
124
125#### `.single(fieldname)`
126
127Accept a single file with the name `fieldname`. The single file will be stored
128in `req.file`.
129
130#### `.array(fieldname[, maxCount])`
131
132Accept an array of files, all with the name `fieldname`. Optionally error out if
133more than `maxCount` files are uploaded. The array of files will be stored in
134`req.files`.
135
136#### `.fields(fields)`
137
138Accept a mix of files, specified by `fields`. An object with arrays of files
139will be stored in `req.files`.
140
141`fields` should be an array of objects with `name` and optionally a `maxCount`.
142Example:
143
144```javascript
145[
146 { name: 'avatar', maxCount: 1 },
147 { name: 'gallery', maxCount: 8 }
148]
149```
150
151#### `.none()`
152
153Accept only text fields. If any file upload is made, error with code
154"LIMIT\_UNEXPECTED\_FILE" will be issued.
155
156#### `.any()`
157
158Accepts all files that comes over the wire. An array of files will be stored in
159`req.files`.
160
161**WARNING:** Make sure that you always handle the files that a user uploads.
162Never add multer as a global middleware since a malicious user could upload
163files to a route that you didn't anticipate. Only use this function on routes
164where you are handling the uploaded files.
165
166### `storage`
167
168#### `DiskStorage`
169
170The disk storage engine gives you full control on storing files to disk.
171
172```javascript
173var storage = multer.diskStorage({
174 destination: function (req, file, cb) {
175 cb(null, '/tmp/my-uploads')
176 },
177 filename: function (req, file, cb) {
178 cb(null, file.fieldname + '-' + Date.now())
179 }
180})
181
182var upload = multer({ storage: storage })
183```
184
185There are two options available, `destination` and `filename`. They are both
186functions that determine where the file should be stored.
187
188`destination` is used to determine within which folder the uploaded files should
189be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no
190`destination` is given, the operating system's default directory for temporary
191files is used.
192
193**Note:** You are responsible for creating the directory when providing
194`destination` as a function. When passing a string, multer will make sure that
195the directory is created for you.
196
197`filename` is used to determine what the file should be named inside the folder.
198If no `filename` is given, each file will be given a random name that doesn't
199include any file extension.
200
201**Note:** Multer will not append any file extension for you, your function
202should return a filename complete with an file extension.
203
204Each function gets passed both the request (`req`) and some information about
205the file (`file`) to aid with the decision.
206
207Note that `req.body` might not have been fully populated yet. It depends on the
208order that the client transmits fields and files to the server.
209
210#### `MemoryStorage`
211
212The memory storage engine stores the files in memory as `Buffer` objects. It
213doesn't have any options.
214
215```javascript
216var storage = multer.memoryStorage()
217var upload = multer({ storage: storage })
218```
219
220When using memory storage, the file info will contain a field called
221`buffer` that contains the entire file.
222
223**WARNING**: Uploading very large files, or relatively small files in large
224numbers very quickly, can cause your application to run out of memory when
225memory storage is used.
226
227### `limits`
228
229An 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 on [busboy's page](https://github.com/mscdex/busboy#busboy-methods).
230
231The following integer values are available:
232
233Key | Description | Default
234--- | --- | ---
235`fieldNameSize` | Max field name size | 100 bytes
236`fieldSize` | Max field value size (in bytes) | 1MB
237`fields` | Max number of non-file fields | Infinity
238`fileSize` | For multipart forms, the max file size (in bytes) | Infinity
239`files` | For multipart forms, the max number of file fields | Infinity
240`parts` | For multipart forms, the max number of parts (fields + files) | Infinity
241`headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000
242
243Specifying the limits can help protect your site against denial of service (DoS) attacks.
244
245### `fileFilter`
246
247Set this to a function to control which files should be uploaded and which
248should be skipped. The function should look like this:
249
250```javascript
251function fileFilter (req, file, cb) {
252
253 // The function should call `cb` with a boolean
254 // to indicate if the file should be accepted
255
256 // To reject this file pass `false`, like so:
257 cb(null, false)
258
259 // To accept the file pass `true`, like so:
260 cb(null, true)
261
262 // You can always pass an error if something goes wrong:
263 cb(new Error('I don\'t have a clue!'))
264
265}
266```
267
268## Error handling
269
270When encountering an error, Multer will delegate the error to Express. You can
271display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html).
272
273If you want to catch errors specifically from Multer, you can call the
274middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/master/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).
275
276```javascript
277var multer = require('multer')
278var upload = multer().single('avatar')
279
280app.post('/profile', function (req, res) {
281 upload(req, res, function (err) {
282 if (err instanceof multer.MulterError) {
283 // A Multer error occurred when uploading.
284 } else if (err) {
285 // An unknown error occurred when uploading.
286 }
287
288 // Everything went fine.
289 })
290})
291```
292
293## Custom storage engine
294
295For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/master/StorageEngine.md).
296
297## License
298
299[MIT](LICENSE)