@marblejs/middleware-multipart
A multipart/form-data middleware based on busboy library.

Installation

1
yarn add @marblejs/middleware-multipart
Copied!
Requires @marblejs/core to be installed.

Importing

1
import { multipart$ } from '@marblejs/middleware-multipart';
Copied!

Type declaration

1
multipart$ :: ParserOpts -> HttpMiddlewareEffect
Copied!

Parameters

parameter
definition
options
<optional> ParserOpts
ParserOpts
parameter
definition
files
<optional> Array<string>
stream
<optional> StreamHandler
maxFileSize
<optional> number
maxFileCount
<optional> number
maxFieldSize
<optional> number
maxFieldCount
<optional> number

Usage

Make sure that you always handle the files that a user uploads. Never add it as a global middleware since a malicious user could upload files to a route that you didn't handle. Only use this it on routes where you are handling the uploaded files.
In-memory storage:
1
import { multipart$ } from '@marblejs/middleware-multipart';
2
3
const effect$ = r.pipe(
4
r.matchPath('/'),
5
r.matchType('POST'),
6
r.useEffect(req$ => req$.pipe(
7
use(multipart$()),
8
map(req => ({ body: {
9
files: req.files, // file data
10
body: req.body, // all incoming body fields
11
}}))
12
)));
Copied!
Out-of-memory storage:
1
import { multipart$, StreamHandler } from '@marblejs/middleware-multipart';
2
3
const stream: StreamHandler = ({ file, fieldname }) => {
4
// stream here incoming file to different location...
5
const destination = // ... and grab the persisted file location
6
return of({ destination });
7
};
8
9
const effect$ = r.pipe(
10
r.matchPath('/'),
11
r.matchType('POST'),
12
r.useEffect(req$ => req$.pipe(
13
use(multipart$({
14
stream,
15
maxFileCount: 1,
16
files: ['image_1'],
17
})),
18
map(req => ({ body: {
19
files: req.files['image_1'], // file data
20
body: req.body, // all incoming body fields
21
}}))
22
)));
Copied!
You can intercept incoming files and stream them to the different place, eg. to OS filesystem or AWS S3 bucket. The prervious example shows how you can specify constraints for multipart/form-data parsing the accepts only one image_1 field.
Each file included inside req.files object contains the following information:
key
description
fieldname
Field name specified in the form
filename
Name of the file on the user's computer
encoding
Encoding type of the file
mimetype
Mime type of the file
size
Size of the file in bytes (in-memory parsing)
destination
The place in which the file has been saved (if not in-memory parsing)
buffer
A Buffer of the entire file (in-memory parsing)
You can define the following middleware options:
key
description
maxFileCount
The total count of files that can be sent
maxFieldCount
The total count of fields that can be sent
maxFileSize
The max possible file size in bytes
files
An array of acceptable field names
stream
A handler which you can use to stream incoming files to different location
Last modified 1yr ago