@depup/multer 2.0.2-depup.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ Copyright (c) 2014 Hage Yaapa <[http://www.hacksparrow.com](http://www.hacksparrow.com)>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,348 @@
1
+ # Multer [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][test-image]][test-url] [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
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
+ | | |
13
+ | ------------------------------------------------------------------------------ | --------------- |
14
+ | [العربية](https://github.com/expressjs/multer/blob/main/doc/README-ar.md) | Arabic |
15
+ | [简体中文](https://github.com/expressjs/multer/blob/main/doc/README-zh-cn.md) | Chinese |
16
+ | [Français](https://github.com/expressjs/multer/blob/main/doc/README-fr.md) | French |
17
+ | [한국어](https://github.com/expressjs/multer/blob/main/doc/README-ko.md) | Korean |
18
+ | [Português](https://github.com/expressjs/multer/blob/main/doc/README-pt-br.md) | Portuguese (BR) |
19
+ | [Русский язык](https://github.com/expressjs/multer/blob/main/doc/README-ru.md) | Russian |
20
+ | [Español](https://github.com/expressjs/multer/blob/main/doc/README-es.md) | Spanish |
21
+ | [O'zbek tili](https://github.com/expressjs/multer/blob/main/doc/README-uz.md) | Uzbek |
22
+ | [Việt Nam](https://github.com/expressjs/multer/blob/main/doc/README-vi.md) | Vietnamese |
23
+
24
+ ## Installation
25
+
26
+ ```sh
27
+ $ npm install multer
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ 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.
33
+
34
+ Basic usage example:
35
+
36
+ Don't forget the `enctype="multipart/form-data"` in your form.
37
+
38
+ ```html
39
+ <form action="/profile" method="post" enctype="multipart/form-data">
40
+ <input type="file" name="avatar" />
41
+ </form>
42
+ ```
43
+
44
+ ```javascript
45
+ const express = require('express')
46
+ const multer = require('multer')
47
+ const upload = multer({ dest: 'uploads/' })
48
+
49
+ const app = express()
50
+
51
+ app.post('/profile', upload.single('avatar'), function (req, res, next) {
52
+ // req.file is the `avatar` file
53
+ // req.body will hold the text fields, if there were any
54
+ })
55
+
56
+ app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
57
+ // req.files is array of `photos` files
58
+ // req.body will contain the text fields, if there were any
59
+ })
60
+
61
+ const uploadMiddleware = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
62
+ app.post('/cool-profile', uploadMiddleware, function (req, res, next) {
63
+ // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
64
+ //
65
+ // e.g.
66
+ // req.files['avatar'][0] -> File
67
+ // req.files['gallery'] -> Array
68
+ //
69
+ // req.body will contain the text fields, if there were any
70
+ })
71
+ ```
72
+
73
+ In case you need to handle a text-only multipart form, you should use the `.none()` method:
74
+
75
+ ```javascript
76
+ const express = require('express')
77
+ const app = express()
78
+ const multer = require('multer')
79
+ const upload = multer()
80
+
81
+ app.post('/profile', upload.none(), function (req, res, next) {
82
+ // req.body contains the text fields
83
+ })
84
+ ```
85
+
86
+ Here's an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields:
87
+
88
+ ```html
89
+ <form action="/stats" enctype="multipart/form-data" method="post">
90
+ <div class="form-group">
91
+ <input type="file" class="form-control-file" name="uploaded_file">
92
+ <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
93
+ <input type="submit" value="Get me the stats!" class="btn btn-default">
94
+ </div>
95
+ </form>
96
+ ```
97
+
98
+ Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail:
99
+
100
+ ```javascript
101
+ const multer = require('multer')
102
+ const upload = multer({ dest: './public/data/uploads/' })
103
+ app.post('/stats', upload.single('uploaded_file'), function (req, res) {
104
+ // req.file is the name of your file in the form above, here 'uploaded_file'
105
+ // req.body will hold the text fields, if there were any
106
+ console.log(req.file, req.body)
107
+ });
108
+ ```
109
+
110
+
111
+
112
+ ## API
113
+
114
+ ### File information
115
+
116
+ Each file contains the following information:
117
+
118
+ Key | Description | Note
119
+ --- | --- | ---
120
+ `fieldname` | Field name specified in the form |
121
+ `originalname` | Name of the file on the user's computer |
122
+ `encoding` | Encoding type of the file |
123
+ `mimetype` | Mime type of the file |
124
+ `size` | Size of the file in bytes |
125
+ `destination` | The folder to which the file has been saved | `DiskStorage`
126
+ `filename` | The name of the file within the `destination` | `DiskStorage`
127
+ `path` | The full path to the uploaded file | `DiskStorage`
128
+ `buffer` | A `Buffer` of the entire file | `MemoryStorage`
129
+
130
+ ### `multer(opts)`
131
+
132
+ Multer accepts an options object, the most basic of which is the `dest`
133
+ property, which tells Multer where to upload the files. In case you omit the
134
+ options object, the files will be kept in memory and never written to disk.
135
+
136
+ By default, Multer will rename the files so as to avoid naming conflicts. The
137
+ renaming function can be customized according to your needs.
138
+
139
+ The following are the options that can be passed to Multer.
140
+
141
+ Key | Description
142
+ --- | ---
143
+ `dest` or `storage` | Where to store the files
144
+ `fileFilter` | Function to control which files are accepted
145
+ `limits` | Limits of the uploaded data
146
+ `preservePath` | Keep the full path of files instead of just the base name
147
+
148
+ In an average web app, only `dest` might be required, and configured as shown in
149
+ the following example.
150
+
151
+ ```javascript
152
+ const upload = multer({ dest: 'uploads/' })
153
+ ```
154
+
155
+ If you want more control over your uploads, you'll want to use the `storage`
156
+ option instead of `dest`. Multer ships with storage engines `DiskStorage`
157
+ and `MemoryStorage`; More engines are available from third parties.
158
+
159
+ #### `.single(fieldname)`
160
+
161
+ Accept a single file with the name `fieldname`. The single file will be stored
162
+ in `req.file`.
163
+
164
+ #### `.array(fieldname[, maxCount])`
165
+
166
+ Accept an array of files, all with the name `fieldname`. Optionally error out if
167
+ more than `maxCount` files are uploaded. The array of files will be stored in
168
+ `req.files`.
169
+
170
+ #### `.fields(fields)`
171
+
172
+ Accept a mix of files, specified by `fields`. An object with arrays of files
173
+ will be stored in `req.files`.
174
+
175
+ `fields` should be an array of objects with `name` and optionally a `maxCount`.
176
+ Example:
177
+
178
+ ```javascript
179
+ [
180
+ { name: 'avatar', maxCount: 1 },
181
+ { name: 'gallery', maxCount: 8 }
182
+ ]
183
+ ```
184
+
185
+ #### `.none()`
186
+
187
+ Accept only text fields. If any file upload is made, error with code
188
+ "LIMIT\_UNEXPECTED\_FILE" will be issued.
189
+
190
+ #### `.any()`
191
+
192
+ Accepts all files that comes over the wire. An array of files will be stored in
193
+ `req.files`.
194
+
195
+ **WARNING:** Make sure that you always handle the files that a user uploads.
196
+ Never add multer as a global middleware since a malicious user could upload
197
+ files to a route that you didn't anticipate. Only use this function on routes
198
+ where you are handling the uploaded files.
199
+
200
+ ### `storage`
201
+
202
+ #### `DiskStorage`
203
+
204
+ The disk storage engine gives you full control on storing files to disk.
205
+
206
+ ```javascript
207
+ const storage = multer.diskStorage({
208
+ destination: function (req, file, cb) {
209
+ cb(null, '/tmp/my-uploads')
210
+ },
211
+ filename: function (req, file, cb) {
212
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
213
+ cb(null, file.fieldname + '-' + uniqueSuffix)
214
+ }
215
+ })
216
+
217
+ const upload = multer({ storage: storage })
218
+ ```
219
+
220
+ There are two options available, `destination` and `filename`. They are both
221
+ functions that determine where the file should be stored.
222
+
223
+ `destination` is used to determine within which folder the uploaded files should
224
+ be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no
225
+ `destination` is given, the operating system's default directory for temporary
226
+ files is used.
227
+
228
+ **Note:** You are responsible for creating the directory when providing
229
+ `destination` as a function. When passing a string, multer will make sure that
230
+ the directory is created for you.
231
+
232
+ `filename` is used to determine what the file should be named inside the folder.
233
+ If no `filename` is given, each file will be given a random name that doesn't
234
+ include any file extension.
235
+
236
+ **Note:** Multer will not append any file extension for you, your function
237
+ should return a filename complete with a file extension.
238
+
239
+ Each function gets passed both the request (`req`) and some information about
240
+ the file (`file`) to aid with the decision.
241
+
242
+ Note that `req.body` might not have been fully populated yet. It depends on the
243
+ order that the client transmits fields and files to the server.
244
+
245
+ For understanding the calling convention used in the callback (needing to pass
246
+ null as the first param), refer to
247
+ [Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors)
248
+
249
+ #### `MemoryStorage`
250
+
251
+ The memory storage engine stores the files in memory as `Buffer` objects. It
252
+ doesn't have any options.
253
+
254
+ ```javascript
255
+ const storage = multer.memoryStorage()
256
+ const upload = multer({ storage: storage })
257
+ ```
258
+
259
+ When using memory storage, the file info will contain a field called
260
+ `buffer` that contains the entire file.
261
+
262
+ **WARNING**: Uploading very large files, or relatively small files in large
263
+ numbers very quickly, can cause your application to run out of memory when
264
+ memory storage is used.
265
+
266
+ ### `limits`
267
+
268
+ 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).
269
+
270
+ The following integer values are available:
271
+
272
+ Key | Description | Default
273
+ --- | --- | ---
274
+ `fieldNameSize` | Max field name size | 100 bytes
275
+ `fieldSize` | Max field value size (in bytes) | 1MB
276
+ `fields` | Max number of non-file fields | Infinity
277
+ `fileSize` | For multipart forms, the max file size (in bytes) | Infinity
278
+ `files` | For multipart forms, the max number of file fields | Infinity
279
+ `parts` | For multipart forms, the max number of parts (fields + files) | Infinity
280
+ `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000
281
+
282
+ Specifying the limits can help protect your site against denial of service (DoS) attacks.
283
+
284
+ ### `fileFilter`
285
+
286
+ Set this to a function to control which files should be uploaded and which
287
+ should be skipped. The function should look like this:
288
+
289
+ ```javascript
290
+ function fileFilter (req, file, cb) {
291
+
292
+ // The function should call `cb` with a boolean
293
+ // to indicate if the file should be accepted
294
+
295
+ // To reject this file pass `false`, like so:
296
+ cb(null, false)
297
+
298
+ // To accept the file pass `true`, like so:
299
+ cb(null, true)
300
+
301
+ // You can always pass an error if something goes wrong:
302
+ cb(new Error('I don\'t have a clue!'))
303
+
304
+ }
305
+ ```
306
+
307
+ ## Error handling
308
+
309
+ When encountering an error, Multer will delegate the error to Express. You can
310
+ display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html).
311
+
312
+ If you want to catch errors specifically from Multer, you can call the
313
+ middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).
314
+
315
+ ```javascript
316
+ const multer = require('multer')
317
+ const upload = multer().single('avatar')
318
+
319
+ app.post('/profile', function (req, res) {
320
+ upload(req, res, function (err) {
321
+ if (err instanceof multer.MulterError) {
322
+ // A Multer error occurred when uploading.
323
+ } else if (err) {
324
+ // An unknown error occurred when uploading.
325
+ }
326
+
327
+ // Everything went fine.
328
+ })
329
+ })
330
+ ```
331
+
332
+ ## Custom storage engine
333
+
334
+ For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/main/StorageEngine.md).
335
+
336
+ ## License
337
+
338
+ [MIT](LICENSE)
339
+
340
+ [ci-image]: https://github.com/expressjs/multer/actions/workflows/ci.yml/badge.svg
341
+ [ci-url]: https://github.com/expressjs/multer/actions/workflows/ci.yml
342
+ [test-url]: https://coveralls.io/r/expressjs/multer?branch=main
343
+ [test-image]: https://badgen.net/coveralls/c/github/expressjs/multer/main
344
+ [npm-downloads-image]: https://badgen.net/npm/dm/multer
345
+ [npm-url]: https://npmjs.org/package/multer
346
+ [npm-version-image]: https://badgen.net/npm/v/multer
347
+ [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/multer/badge
348
+ [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/multer
package/index.js ADDED
@@ -0,0 +1,104 @@
1
+ var makeMiddleware = require('./lib/make-middleware')
2
+
3
+ var diskStorage = require('./storage/disk')
4
+ var memoryStorage = require('./storage/memory')
5
+ var MulterError = require('./lib/multer-error')
6
+
7
+ function allowAll (req, file, cb) {
8
+ cb(null, true)
9
+ }
10
+
11
+ function Multer (options) {
12
+ if (options.storage) {
13
+ this.storage = options.storage
14
+ } else if (options.dest) {
15
+ this.storage = diskStorage({ destination: options.dest })
16
+ } else {
17
+ this.storage = memoryStorage()
18
+ }
19
+
20
+ this.limits = options.limits
21
+ this.preservePath = options.preservePath
22
+ this.fileFilter = options.fileFilter || allowAll
23
+ }
24
+
25
+ Multer.prototype._makeMiddleware = function (fields, fileStrategy) {
26
+ function setup () {
27
+ var fileFilter = this.fileFilter
28
+ var filesLeft = Object.create(null)
29
+
30
+ fields.forEach(function (field) {
31
+ if (typeof field.maxCount === 'number') {
32
+ filesLeft[field.name] = field.maxCount
33
+ } else {
34
+ filesLeft[field.name] = Infinity
35
+ }
36
+ })
37
+
38
+ function wrappedFileFilter (req, file, cb) {
39
+ if ((filesLeft[file.fieldname] || 0) <= 0) {
40
+ return cb(new MulterError('LIMIT_UNEXPECTED_FILE', file.fieldname))
41
+ }
42
+
43
+ filesLeft[file.fieldname] -= 1
44
+ fileFilter(req, file, cb)
45
+ }
46
+
47
+ return {
48
+ limits: this.limits,
49
+ preservePath: this.preservePath,
50
+ storage: this.storage,
51
+ fileFilter: wrappedFileFilter,
52
+ fileStrategy: fileStrategy
53
+ }
54
+ }
55
+
56
+ return makeMiddleware(setup.bind(this))
57
+ }
58
+
59
+ Multer.prototype.single = function (name) {
60
+ return this._makeMiddleware([{ name: name, maxCount: 1 }], 'VALUE')
61
+ }
62
+
63
+ Multer.prototype.array = function (name, maxCount) {
64
+ return this._makeMiddleware([{ name: name, maxCount: maxCount }], 'ARRAY')
65
+ }
66
+
67
+ Multer.prototype.fields = function (fields) {
68
+ return this._makeMiddleware(fields, 'OBJECT')
69
+ }
70
+
71
+ Multer.prototype.none = function () {
72
+ return this._makeMiddleware([], 'NONE')
73
+ }
74
+
75
+ Multer.prototype.any = function () {
76
+ function setup () {
77
+ return {
78
+ limits: this.limits,
79
+ preservePath: this.preservePath,
80
+ storage: this.storage,
81
+ fileFilter: this.fileFilter,
82
+ fileStrategy: 'ARRAY'
83
+ }
84
+ }
85
+
86
+ return makeMiddleware(setup.bind(this))
87
+ }
88
+
89
+ function multer (options) {
90
+ if (options === undefined) {
91
+ return new Multer({})
92
+ }
93
+
94
+ if (typeof options === 'object' && options !== null) {
95
+ return new Multer(options)
96
+ }
97
+
98
+ throw new TypeError('Expected object for argument options')
99
+ }
100
+
101
+ module.exports = multer
102
+ module.exports.diskStorage = diskStorage
103
+ module.exports.memoryStorage = memoryStorage
104
+ module.exports.MulterError = MulterError
package/lib/counter.js ADDED
@@ -0,0 +1,28 @@
1
+ var EventEmitter = require('events').EventEmitter
2
+
3
+ function Counter () {
4
+ EventEmitter.call(this)
5
+ this.value = 0
6
+ }
7
+
8
+ Counter.prototype = Object.create(EventEmitter.prototype)
9
+
10
+ Counter.prototype.increment = function increment () {
11
+ this.value++
12
+ }
13
+
14
+ Counter.prototype.decrement = function decrement () {
15
+ if (--this.value === 0) this.emit('zero')
16
+ }
17
+
18
+ Counter.prototype.isZero = function isZero () {
19
+ return (this.value === 0)
20
+ }
21
+
22
+ Counter.prototype.onceZero = function onceZero (fn) {
23
+ if (this.isZero()) return fn()
24
+
25
+ this.once('zero', fn)
26
+ }
27
+
28
+ module.exports = Counter
@@ -0,0 +1,67 @@
1
+ var objectAssign = require('object-assign')
2
+
3
+ function arrayRemove (arr, item) {
4
+ var idx = arr.indexOf(item)
5
+ if (~idx) arr.splice(idx, 1)
6
+ }
7
+
8
+ function FileAppender (strategy, req) {
9
+ this.strategy = strategy
10
+ this.req = req
11
+
12
+ switch (strategy) {
13
+ case 'NONE': break
14
+ case 'VALUE': break
15
+ case 'ARRAY': req.files = []; break
16
+ case 'OBJECT': req.files = Object.create(null); break
17
+ default: throw new Error('Unknown file strategy: ' + strategy)
18
+ }
19
+ }
20
+
21
+ FileAppender.prototype.insertPlaceholder = function (file) {
22
+ var placeholder = {
23
+ fieldname: file.fieldname
24
+ }
25
+
26
+ switch (this.strategy) {
27
+ case 'NONE': break
28
+ case 'VALUE': break
29
+ case 'ARRAY': this.req.files.push(placeholder); break
30
+ case 'OBJECT':
31
+ if (this.req.files[file.fieldname]) {
32
+ this.req.files[file.fieldname].push(placeholder)
33
+ } else {
34
+ this.req.files[file.fieldname] = [placeholder]
35
+ }
36
+ break
37
+ }
38
+
39
+ return placeholder
40
+ }
41
+
42
+ FileAppender.prototype.removePlaceholder = function (placeholder) {
43
+ switch (this.strategy) {
44
+ case 'NONE': break
45
+ case 'VALUE': break
46
+ case 'ARRAY': arrayRemove(this.req.files, placeholder); break
47
+ case 'OBJECT':
48
+ if (this.req.files[placeholder.fieldname].length === 1) {
49
+ delete this.req.files[placeholder.fieldname]
50
+ } else {
51
+ arrayRemove(this.req.files[placeholder.fieldname], placeholder)
52
+ }
53
+ break
54
+ }
55
+ }
56
+
57
+ FileAppender.prototype.replacePlaceholder = function (placeholder, file) {
58
+ if (this.strategy === 'VALUE') {
59
+ this.req.file = file
60
+ return
61
+ }
62
+
63
+ delete placeholder.fieldname
64
+ objectAssign(placeholder, file)
65
+ }
66
+
67
+ module.exports = FileAppender
@@ -0,0 +1,194 @@
1
+ var is = require('type-is')
2
+ var Busboy = require('busboy')
3
+ var extend = require('xtend')
4
+ var appendField = require('append-field')
5
+
6
+ var Counter = require('./counter')
7
+ var MulterError = require('./multer-error')
8
+ var FileAppender = require('./file-appender')
9
+ var removeUploadedFiles = require('./remove-uploaded-files')
10
+
11
+ function drainStream (stream) {
12
+ stream.on('readable', () => {
13
+ while (stream.read() !== null) {}
14
+ })
15
+ }
16
+
17
+ function makeMiddleware (setup) {
18
+ return function multerMiddleware (req, res, next) {
19
+ if (!is(req, ['multipart'])) return next()
20
+
21
+ var options = setup()
22
+
23
+ var limits = options.limits
24
+ var storage = options.storage
25
+ var fileFilter = options.fileFilter
26
+ var fileStrategy = options.fileStrategy
27
+ var preservePath = options.preservePath
28
+
29
+ req.body = Object.create(null)
30
+
31
+ req.on('error', function (err) {
32
+ abortWithError(err)
33
+ })
34
+
35
+ var busboy
36
+
37
+ try {
38
+ busboy = Busboy({ headers: req.headers, limits: limits, preservePath: preservePath })
39
+ } catch (err) {
40
+ return next(err)
41
+ }
42
+
43
+ var appender = new FileAppender(fileStrategy, req)
44
+ var isDone = false
45
+ var readFinished = false
46
+ var errorOccured = false
47
+ var pendingWrites = new Counter()
48
+ var uploadedFiles = []
49
+
50
+ function done (err) {
51
+ if (isDone) return
52
+ isDone = true
53
+ req.unpipe(busboy)
54
+ drainStream(req)
55
+ req.resume()
56
+ setImmediate(() => {
57
+ busboy.removeAllListeners()
58
+ })
59
+ next(err)
60
+ }
61
+
62
+ function indicateDone () {
63
+ if (readFinished && pendingWrites.isZero() && !errorOccured) done()
64
+ }
65
+
66
+ function abortWithError (uploadError) {
67
+ if (errorOccured) return
68
+ errorOccured = true
69
+
70
+ pendingWrites.onceZero(function () {
71
+ function remove (file, cb) {
72
+ storage._removeFile(req, file, cb)
73
+ }
74
+
75
+ removeUploadedFiles(uploadedFiles, remove, function (err, storageErrors) {
76
+ if (err) return done(err)
77
+
78
+ uploadError.storageErrors = storageErrors
79
+ done(uploadError)
80
+ })
81
+ })
82
+ }
83
+
84
+ function abortWithCode (code, optionalField) {
85
+ abortWithError(new MulterError(code, optionalField))
86
+ }
87
+
88
+ // handle text field data
89
+ busboy.on('field', function (fieldname, value, { nameTruncated, valueTruncated }) {
90
+ if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
91
+ if (nameTruncated) return abortWithCode('LIMIT_FIELD_KEY')
92
+ if (valueTruncated) return abortWithCode('LIMIT_FIELD_VALUE', fieldname)
93
+
94
+ // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
95
+ if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) {
96
+ if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY')
97
+ }
98
+
99
+ appendField(req.body, fieldname, value)
100
+ })
101
+
102
+ // handle files
103
+ busboy.on('file', function (fieldname, fileStream, { filename, encoding, mimeType }) {
104
+ var pendingWritesIncremented = false
105
+
106
+ fileStream.on('error', function (err) {
107
+ if (pendingWritesIncremented) {
108
+ pendingWrites.decrement()
109
+ }
110
+ abortWithError(err)
111
+ })
112
+
113
+ if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
114
+
115
+ // don't attach to the files object, if there is no file
116
+ if (!filename) return fileStream.resume()
117
+
118
+ // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
119
+ if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) {
120
+ if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY')
121
+ }
122
+
123
+ var file = {
124
+ fieldname: fieldname,
125
+ originalname: filename,
126
+ encoding: encoding,
127
+ mimetype: mimeType
128
+ }
129
+
130
+ var placeholder = appender.insertPlaceholder(file)
131
+
132
+ fileFilter(req, file, function (err, includeFile) {
133
+ if (err) {
134
+ appender.removePlaceholder(placeholder)
135
+ return abortWithError(err)
136
+ }
137
+
138
+ if (!includeFile) {
139
+ appender.removePlaceholder(placeholder)
140
+ return fileStream.resume()
141
+ }
142
+
143
+ var aborting = false
144
+ pendingWritesIncremented = true
145
+ pendingWrites.increment()
146
+
147
+ Object.defineProperty(file, 'stream', {
148
+ configurable: true,
149
+ enumerable: false,
150
+ value: fileStream
151
+ })
152
+
153
+ fileStream.on('limit', function () {
154
+ aborting = true
155
+ abortWithCode('LIMIT_FILE_SIZE', fieldname)
156
+ })
157
+
158
+ storage._handleFile(req, file, function (err, info) {
159
+ if (aborting) {
160
+ appender.removePlaceholder(placeholder)
161
+ uploadedFiles.push(extend(file, info))
162
+ return pendingWrites.decrement()
163
+ }
164
+
165
+ if (err) {
166
+ appender.removePlaceholder(placeholder)
167
+ pendingWrites.decrement()
168
+ return abortWithError(err)
169
+ }
170
+
171
+ var fileInfo = extend(file, info)
172
+
173
+ appender.replacePlaceholder(placeholder, fileInfo)
174
+ uploadedFiles.push(fileInfo)
175
+ pendingWrites.decrement()
176
+ indicateDone()
177
+ })
178
+ })
179
+ })
180
+
181
+ busboy.on('error', function (err) { abortWithError(err) })
182
+ busboy.on('partsLimit', function () { abortWithCode('LIMIT_PART_COUNT') })
183
+ busboy.on('filesLimit', function () { abortWithCode('LIMIT_FILE_COUNT') })
184
+ busboy.on('fieldsLimit', function () { abortWithCode('LIMIT_FIELD_COUNT') })
185
+ busboy.on('close', function () {
186
+ readFinished = true
187
+ indicateDone()
188
+ })
189
+
190
+ req.pipe(busboy)
191
+ }
192
+ }
193
+
194
+ module.exports = makeMiddleware
@@ -0,0 +1,24 @@
1
+ var util = require('util')
2
+
3
+ var errorMessages = {
4
+ LIMIT_PART_COUNT: 'Too many parts',
5
+ LIMIT_FILE_SIZE: 'File too large',
6
+ LIMIT_FILE_COUNT: 'Too many files',
7
+ LIMIT_FIELD_KEY: 'Field name too long',
8
+ LIMIT_FIELD_VALUE: 'Field value too long',
9
+ LIMIT_FIELD_COUNT: 'Too many fields',
10
+ LIMIT_UNEXPECTED_FILE: 'Unexpected field',
11
+ MISSING_FIELD_NAME: 'Field name missing'
12
+ }
13
+
14
+ function MulterError (code, field) {
15
+ Error.captureStackTrace(this, this.constructor)
16
+ this.name = this.constructor.name
17
+ this.message = errorMessages[code]
18
+ this.code = code
19
+ if (field) this.field = field
20
+ }
21
+
22
+ util.inherits(MulterError, Error)
23
+
24
+ module.exports = MulterError
@@ -0,0 +1,28 @@
1
+ function removeUploadedFiles (uploadedFiles, remove, cb) {
2
+ var length = uploadedFiles.length
3
+ var errors = []
4
+
5
+ if (length === 0) return cb(null, errors)
6
+
7
+ function handleFile (idx) {
8
+ var file = uploadedFiles[idx]
9
+
10
+ remove(file, function (err) {
11
+ if (err) {
12
+ err.file = file
13
+ err.field = file.fieldname
14
+ errors.push(err)
15
+ }
16
+
17
+ if (idx < length - 1) {
18
+ handleFile(idx + 1)
19
+ } else {
20
+ cb(null, errors)
21
+ }
22
+ })
23
+ }
24
+
25
+ handleFile(0)
26
+ }
27
+
28
+ module.exports = removeUploadedFiles
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@depup/multer",
3
+ "description": "Middleware for handling `multipart/form-data`.",
4
+ "version": "2.0.2-depup.1",
5
+ "contributors": [
6
+ "Hage Yaapa <captain@hacksparrow.com> (http://www.hacksparrow.com)",
7
+ "Jaret Pfluger <https://github.com/jpfluger>",
8
+ "Linus Unnebäck <linus@folkdatorn.se>"
9
+ ],
10
+ "license": "MIT",
11
+ "repository": "expressjs/multer",
12
+ "keywords": [
13
+ "form",
14
+ "post",
15
+ "multipart",
16
+ "form-data",
17
+ "formdata",
18
+ "express",
19
+ "middleware"
20
+ ],
21
+ "dependencies": {
22
+ "append-field": "^2.0.0",
23
+ "busboy": "^1.6.0",
24
+ "concat-stream": "^2.0.0",
25
+ "mkdirp": "^3.0.1",
26
+ "object-assign": "^4.1.1",
27
+ "type-is": "^2.0.1",
28
+ "xtend": "^4.0.2"
29
+ },
30
+ "devDependencies": {
31
+ "deep-equal": "^2.2.3",
32
+ "express": "^5.2.1",
33
+ "form-data": "^4.0.5",
34
+ "fs-temp": "^2.0.1",
35
+ "mocha": "^11.7.5",
36
+ "nyc": "^17.1.0",
37
+ "rimraf": "^6.1.2",
38
+ "standard": "^17.1.2",
39
+ "testdata-w3c-json-form": "^1.0.0"
40
+ },
41
+ "engines": {
42
+ "node": ">= 10.16.0"
43
+ },
44
+ "files": [
45
+ "LICENSE",
46
+ "index.js",
47
+ "storage/",
48
+ "lib/"
49
+ ],
50
+ "scripts": {
51
+ "lint": "standard",
52
+ "lint:fix": "standard --fix",
53
+ "test": "mocha --reporter spec --exit --check-leaks test/",
54
+ "test-ci": "nyc --reporter=lcov --reporter=text npm test",
55
+ "test-cov": "nyc --reporter=html --reporter=text npm test"
56
+ }
57
+ }
@@ -0,0 +1,66 @@
1
+ var fs = require('fs')
2
+ var os = require('os')
3
+ var path = require('path')
4
+ var crypto = require('crypto')
5
+ var mkdirp = require('mkdirp')
6
+
7
+ function getFilename (req, file, cb) {
8
+ crypto.randomBytes(16, function (err, raw) {
9
+ cb(err, err ? undefined : raw.toString('hex'))
10
+ })
11
+ }
12
+
13
+ function getDestination (req, file, cb) {
14
+ cb(null, os.tmpdir())
15
+ }
16
+
17
+ function DiskStorage (opts) {
18
+ this.getFilename = (opts.filename || getFilename)
19
+
20
+ if (typeof opts.destination === 'string') {
21
+ mkdirp.sync(opts.destination)
22
+ this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) }
23
+ } else {
24
+ this.getDestination = (opts.destination || getDestination)
25
+ }
26
+ }
27
+
28
+ DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
29
+ var that = this
30
+
31
+ that.getDestination(req, file, function (err, destination) {
32
+ if (err) return cb(err)
33
+
34
+ that.getFilename(req, file, function (err, filename) {
35
+ if (err) return cb(err)
36
+
37
+ var finalPath = path.join(destination, filename)
38
+ var outStream = fs.createWriteStream(finalPath)
39
+
40
+ file.stream.pipe(outStream)
41
+ outStream.on('error', cb)
42
+ outStream.on('finish', function () {
43
+ cb(null, {
44
+ destination: destination,
45
+ filename: filename,
46
+ path: finalPath,
47
+ size: outStream.bytesWritten
48
+ })
49
+ })
50
+ })
51
+ })
52
+ }
53
+
54
+ DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) {
55
+ var path = file.path
56
+
57
+ delete file.destination
58
+ delete file.filename
59
+ delete file.path
60
+
61
+ fs.unlink(path, cb)
62
+ }
63
+
64
+ module.exports = function (opts) {
65
+ return new DiskStorage(opts)
66
+ }
@@ -0,0 +1,21 @@
1
+ var concat = require('concat-stream')
2
+
3
+ function MemoryStorage (opts) {}
4
+
5
+ MemoryStorage.prototype._handleFile = function _handleFile (req, file, cb) {
6
+ file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
7
+ cb(null, {
8
+ buffer: data,
9
+ size: data.length
10
+ })
11
+ }))
12
+ }
13
+
14
+ MemoryStorage.prototype._removeFile = function _removeFile (req, file, cb) {
15
+ delete file.buffer
16
+ cb(null)
17
+ }
18
+
19
+ module.exports = function (opts) {
20
+ return new MemoryStorage(opts)
21
+ }