@marblejs/middleware-multipart

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

Installation

yarn add @marblejs/middleware-multipart

Requires @marblejs/core to be installed.

Importing

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

Type declaration

multipart$ :: ParserOpts -> HttpMiddlewareEffect

Parameters

ParserOpts

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:

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

const effect$ = r.pipe(
  r.matchPath('/'),
  r.matchType('POST'),
  r.useEffect(req$ => req$.pipe(
    use(multipart$()),
    map(req => ({ body: {
      files: req.files,    // file data
      body: req.body,      // all incoming body fields
    }}))
  )));

Out-of-memory storage:

import { multipart$, StreamHandler } from '@marblejs/middleware-multipart';

const stream: StreamHandler = ({ file, fieldname }) => {
  // stream here incoming file to different location...
  const destination = // ... and grab the persisted file location
  return of({ destination });
};

const effect$ = r.pipe(
  r.matchPath('/'),
  r.matchType('POST'),
  r.useEffect(req$ => req$.pipe(
    use(multipart$({
      stream,
      maxFileCount: 1,
      files: ['image_1'],
    })),
    map(req => ({ body: {
      files: req.files['image_1'],  // file data
      body: req.body,               // all incoming body fields
    }}))
  )));

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:

You can define the following middleware options:

Last updated