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 |
|
3 | Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written
|
4 | on 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 |
|
10 | This 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 |
|
24 | Multer 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 |
|
26 | Basic usage example:
|
27 |
|
28 | Don'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
|
37 | var express = require('express')
|
38 | var multer = require('multer')
|
39 | var upload = multer({ dest: 'uploads/' })
|
40 |
|
41 | var app = express()
|
42 |
|
43 | app.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 |
|
48 | app.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 |
|
53 | var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
|
54 | app.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 |
|
65 | In case you need to handle a text-only multipart form, you should use the `.none()` method:
|
66 |
|
67 | ```javascript
|
68 | var express = require('express')
|
69 | var app = express()
|
70 | var multer = require('multer')
|
71 | var upload = multer()
|
72 |
|
73 | app.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 |
|
82 | Each file contains the following information:
|
83 |
|
84 | Key | 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 |
|
98 | Multer accepts an options object, the most basic of which is the `dest`
|
99 | property, which tells Multer where to upload the files. In case you omit the
|
100 | options object, the files will be kept in memory and never written to disk.
|
101 |
|
102 | By default, Multer will rename the files so as to avoid naming conflicts. The
|
103 | renaming function can be customized according to your needs.
|
104 |
|
105 | The following are the options that can be passed to Multer.
|
106 |
|
107 | Key | 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 |
|
114 | In an average web app, only `dest` might be required, and configured as shown in
|
115 | the following example.
|
116 |
|
117 | ```javascript
|
118 | var upload = multer({ dest: 'uploads/' })
|
119 | ```
|
120 |
|
121 | If you want more control over your uploads, you'll want to use the `storage`
|
122 | option instead of `dest`. Multer ships with storage engines `DiskStorage`
|
123 | and `MemoryStorage`; More engines are available from third parties.
|
124 |
|
125 | #### `.single(fieldname)`
|
126 |
|
127 | Accept a single file with the name `fieldname`. The single file will be stored
|
128 | in `req.file`.
|
129 |
|
130 | #### `.array(fieldname[, maxCount])`
|
131 |
|
132 | Accept an array of files, all with the name `fieldname`. Optionally error out if
|
133 | more than `maxCount` files are uploaded. The array of files will be stored in
|
134 | `req.files`.
|
135 |
|
136 | #### `.fields(fields)`
|
137 |
|
138 | Accept a mix of files, specified by `fields`. An object with arrays of files
|
139 | will be stored in `req.files`.
|
140 |
|
141 | `fields` should be an array of objects with `name` and optionally a `maxCount`.
|
142 | Example:
|
143 |
|
144 | ```javascript
|
145 | [
|
146 | { name: 'avatar', maxCount: 1 },
|
147 | { name: 'gallery', maxCount: 8 }
|
148 | ]
|
149 | ```
|
150 |
|
151 | #### `.none()`
|
152 |
|
153 | Accept only text fields. If any file upload is made, error with code
|
154 | "LIMIT\_UNEXPECTED\_FILE" will be issued.
|
155 |
|
156 | #### `.any()`
|
157 |
|
158 | Accepts 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.
|
162 | Never add multer as a global middleware since a malicious user could upload
|
163 | files to a route that you didn't anticipate. Only use this function on routes
|
164 | where you are handling the uploaded files.
|
165 |
|
166 | ### `storage`
|
167 |
|
168 | #### `DiskStorage`
|
169 |
|
170 | The disk storage engine gives you full control on storing files to disk.
|
171 |
|
172 | ```javascript
|
173 | var 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 |
|
182 | var upload = multer({ storage: storage })
|
183 | ```
|
184 |
|
185 | There are two options available, `destination` and `filename`. They are both
|
186 | functions that determine where the file should be stored.
|
187 |
|
188 | `destination` is used to determine within which folder the uploaded files should
|
189 | be 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
|
191 | files 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
|
195 | the directory is created for you.
|
196 |
|
197 | `filename` is used to determine what the file should be named inside the folder.
|
198 | If no `filename` is given, each file will be given a random name that doesn't
|
199 | include any file extension.
|
200 |
|
201 | **Note:** Multer will not append any file extension for you, your function
|
202 | should return a filename complete with an file extension.
|
203 |
|
204 | Each function gets passed both the request (`req`) and some information about
|
205 | the file (`file`) to aid with the decision.
|
206 |
|
207 | Note that `req.body` might not have been fully populated yet. It depends on the
|
208 | order that the client transmits fields and files to the server.
|
209 |
|
210 | #### `MemoryStorage`
|
211 |
|
212 | The memory storage engine stores the files in memory as `Buffer` objects. It
|
213 | doesn't have any options.
|
214 |
|
215 | ```javascript
|
216 | var storage = multer.memoryStorage()
|
217 | var upload = multer({ storage: storage })
|
218 | ```
|
219 |
|
220 | When 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
|
224 | numbers very quickly, can cause your application to run out of memory when
|
225 | memory storage is used.
|
226 |
|
227 | ### `limits`
|
228 |
|
229 | An 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 |
|
231 | The following integer values are available:
|
232 |
|
233 | Key | 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 |
|
243 | Specifying the limits can help protect your site against denial of service (DoS) attacks.
|
244 |
|
245 | ### `fileFilter`
|
246 |
|
247 | Set this to a function to control which files should be uploaded and which
|
248 | should be skipped. The function should look like this:
|
249 |
|
250 | ```javascript
|
251 | function 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 |
|
270 | When encountering an error, Multer will delegate the error to Express. You can
|
271 | display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html).
|
272 |
|
273 | If you want to catch errors specifically from Multer, you can call the
|
274 | middleware 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
|
277 | var multer = require('multer')
|
278 | var upload = multer().single('avatar')
|
279 |
|
280 | app.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 |
|
295 | For 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)
|