multer middleware

Multer は multipart/form-data を扱うための node.js ミドルウェアで、主にファイルのアップロードに使用されます。 の上に busboyと書かれており、最大限の効率を得ることができます。 の上に busboyと書かれており、最大限の効率を得ることができます。

注意: Multer はマルチパートでないフォームを処理しません (multipart/form-data)。

インストール

Terminal window
npm install multer

multer does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from DefinitelyTyped as a development dependency:

Terminal window
npm install --save-dev @types/multer

使用法

Multer は body オブジェクトと file または files オブジェクトを request オブジェクトに追加します。 body オブジェクトには、フォームのテキストフィールドの値が含まれています。file または files オブジェクトには、フォームを介してアップロードされたファイルが含まれています。 body オブジェクトには、フォームのテキストフィールドの値が含まれています。file または files オブジェクトには、フォームを介してアップロードされたファイルが含まれています。

基本的な使用例:

フォームの`enctype=“multipart/form-data”を忘れないでください。

<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</form>
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
});
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
});
const uploadMiddleware = upload.fields([
{ name: 'avatar', maxCount: 1 },
{ name: 'gallery', maxCount: 8 },
]);
app.post('/cool-profile', uploadMiddleware, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
});

テキストのみのマルチパート形式を扱う必要がある場合は、.none()メソッドを使用してください。

const express = require('express');
const app = express();
const multer = require('multer');
const upload = multer();
app.post('/profile', upload.none(), function (req, res, next) {
// req.body contains the text fields
});

multer が HTML 形式でどのように使用されるかについての例を示します。 multer が HTML 形式でどのように使用されるかについての例を示します。 enctype="multipart/form-data"とname=“uploaded_file”`フィールドの特に注意してください。

<form action="/stats" enctype="multipart/form-data" method="post">
<div class="form-group">
<input type="file" class="form-control-file" name="uploaded_file" />
<input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers" />
<input type="submit" value="Get me the stats!" class="btn btn-default" />
</div>
</form>

次に、javascriptファイルで、ファイルと本文の両方にアクセスするために、これらの行を追加します。アップロード関数のフォームから name フィールドの値を使用することが重要です。これは、リクエストのどのフィールドにファイルを探すべきかをmulterに伝えます。次に、javascriptファイルで、ファイルと本文の両方にアクセスするために、これらの行を追加します。 アップロード関数のフォームから name フィールドの値を使用することが重要です。 これは、リクエストのどのフィールドにファイルを探すべきかをmulterに伝えます。 これらのフィールドが HTML フォームとサーバーで同じでない場合、アップロードに失敗します:

const multer = require('multer');
const upload = multer({ dest: './public/data/uploads/' });
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
// req.file is the name of your file in the form above, here 'uploaded_file'
// req.body will hold the text fields, if there were any
console.log(req.file, req.body);
});

Complete client-side and server-side examples (browser FormData uploads of a blob and of an image) are in the examples/ folder.

API

ファイル情報

各ファイルには以下の情報が含まれています:

キー説明メモ
fieldnameフォームで指定されたフィールド名
originalnameName of the file on the user’s computer, or the full path when preservePath: true
encodingファイルのエンコードタイプ
mimetypeファイルの Mime タイプ
sizeバイト単位のファイルのサイズ
destinationファイルが保存されたフォルダDiskStorage
filenamedestination内のファイルの名前DiskStorage
pathアップロードされたファイルへのフルパスDiskStorage
bufferファイル全体の BufferMemoryStorage

multer(opts)

Multer は options オブジェクトを受け付けます。最も基本的なオブジェクトは dest プロパティで、Multer はファイルのアップロード先を指定します。 オプションオブジェクトを省略した場合、ファイルはメモリに保存され、ディスクに書き込まれることはありません。 オプションオブジェクトを省略した場合、ファイルはメモリに保存され、ディスクに書き込まれることはありません。

デフォルトでは、Multer は名前の衝突を避けるためにファイルの名前を変更します。 の名前変更機能は、必要に応じてカスタマイズできます。 の名前変更機能は、必要に応じてカスタマイズできます。

Multer に渡すことができるオプションは以下のとおりです。

キー説明
defCharsetDefault character set to use for text field values that do not declare one. Default: 'utf8'
defParamCharset拡張パラメータではない (明示的な文字セットを含む) 部品ヘッダーパラメータの値(ファイル名など)に使用するデフォルトの文字セット。 デフォルト: 'latin1' デフォルト: 'latin1'
dest または storageファイルを保存する場所
fileFilter受け入れられるファイルを制御する関数
fileHwmhighWaterMark of each file stream (file.stream). Default: busboy’s default
highWaterMarkhighWaterMark of the multipart parser stream. Default: busboy’s default
limitsアップロードしたデータの制限
preservePathKeep the full client-supplied path in file.originalname instead of just the base name
streamHandlerFunction that feeds the request body to busboy; defaults to req.pipe(busboy)

In an average web app, only dest might be required, and configured as shown in the following example.

const upload = multer({ dest: 'uploads/' });

When preservePath is enabled, Multer passes the incoming filename through with any path segments provided by the client. This is exposed as file.originalname; it does not change the destination folder, create directories, or sanitize the path for you. file.originalname is always client-supplied and should be treated as untrusted; with preservePath it additionally contains the path segments the client sent. Normalize or validate it before using it in a custom filename or storage engine.

アップロードをもっと制御したい場合は、dest の代わりに storage オプションを使用します。 Multer はストレージエンジン DiskStorage と MemoryStorage を搭載しています。より多くのエンジンはサードパーティから入手できます。 Multer はストレージエンジン DiskStorage と MemoryStorage を搭載しています。より多くのエンジンはサードパーティから入手できます。

.single(fieldname)

fieldnameという名前のファイルを受け入れます。 単一のファイルは を req.file に格納します。単一のファイルは を req.file に格納します。

.array(fieldname[, maxCount])

fieldnameという名前のファイルの配列を受け入れます。必要に応じて、 が maxCountファイルよりも大きい場合にエラーが発生します。ワイヤ上にあるすべてのファイルを受け入れます。 ファイルの配列は req.files に格納されます。

Files skipped by fileFilter do not count towards maxCount. Use limits.files to bound how many files are read from a request.

.fields(fields)

fieldsで指定されたファイルのミックスを受け入れます。 fieldsで指定されたファイルのミックスを受け入れます。 ファイル の配列を持つオブジェクトはreq.filesに保存されます。

fieldsは、nameとオプションでmaxCountを持つオブジェクトの配列でなければなりません。 例例

[
{ name: 'avatar', maxCount: 1 },
{ name: 'gallery', maxCount: 8 },
];

.none()

テキストフィールドのみ受け入れます。 If any file upload is made, error with code LIMIT_UNEXPECTED_FILE will be issued.

.any()

Accepts all files that come over the wire. ファイルの配列は req.files に格納されます。

警告: ユーザーがアップロードするファイルを常に処理していることを確認してください。警告: ユーザーがアップロードするファイルを常に処理していることを確認してください。 悪意のあるユーザーが予想していなかったルートに ファイルをアップロードできるため、multer をグローバルミドルウェアとして追加しないでください。 アップロードされたファイルを処理しているルート でのみこの機能を使用してください。アップロードされたファイルを処理しているルート でのみこの機能を使用してください。

storage

DiskStorage

ディスクストレージエンジンは、ディスクにファイルを保存することを完全に制御します。

const crypto = require('crypto');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads');
},
filename: function (req, file, cb) {
crypto.randomBytes(16, function (err, raw) {
if (err) return cb(err);
cb(null, file.fieldname + '-' + raw.toString('hex'));
});
},
});
const upload = multer({ storage: storage });

There are three options available: destination, filename and flush. All of them except flush are functions that determine where the file should be stored.

destination is used to determine within which folder the uploaded files should be stored. これは文字列として与えることもできます(例: '/tmp/uploads)。 destination が指定されていない場合は、一時的な ファイルのオペレーティングシステムのデフォルトディレクトリが使用されます。

注意: 関数として destination を指定するときにディレクトリを作成します。 文字列を渡すとき、multer は ディレクトリが作成されていることを確認します。文字列を渡すとき、multer は ディレクトリが作成されていることを確認します。

destination is used to determine within which folder the uploaded files should be stored. これは文字列として与えることもできます(例: '/tmp/uploads)。 destination が指定されていない場合は、一時的な ファイルのオペレーティングシステムのデフォルトディレクトリが使用されます。

注意: Multer はファイル拡張子を追加しません。あなたの関数 はファイル拡張子の完全なファイル名を返します。

各関数はリクエスト(req)と ファイル(file)に関する情報の両方を渡され、決定を助けます。

req.body はまだ完全に入力されていない可能性があります。これは、クライアントがフィールドとファイルをサーバーに送信する オーダーに依存します。

コールバックで使用される呼び出し規約(最初のパラメータとして null を渡す必要がある)を理解するには、 [Node] を参照してください。 s error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors)

flush is an optional boolean. When set to true, the file data is flushed to disk with an fsync call before the upload handler runs, which prevents data loss if the process or the system crashes while the data is still sitting in the operating system’s page cache. It is disabled by default because forcing a disk flush on every upload has a performance cost. Note that this syncs the file contents only; if the new directory entry must survive a crash as well, fsync the destination directory yourself.

MemoryStorage

メモリストレージエンジンはファイルを Buffer オブジェクトとして保存します。 にはオプションはありません。 It doesn’t have any options.

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

メモリストレージを使用する場合、ファイル情報にはファイル全体を含む buffer というフィールドが含まれます。

WARNING: Uploading very large files, or relatively small files in large numbers very quickly, can cause your application to run out of memory when memory storage is used.

limits

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.

limits can also be a function that receives the request and returns such an object. It is called once per request, before parsing starts, so limits can depend on e.g. the authenticated user:

const upload = multer({
limits: function (req) {
return { fileSize: req.user.maxUploadSize };
},
});

Limits apply to the whole request; there is no per-file limit. To restrict individual files by type or name, use fileFilter or a custom storage engine.

次の整数値が使用できます。

キー説明デフォルト
fieldNameSize最大フィールド名のサイズInfinity
fieldSize最大フィールド値のサイズ (バイト単位)1MB
fieldsファイル以外のフィールドの最大数Infinity
fileSizeマルチパート形式の場合、最大ファイルサイズ(バイト単位)Infinity
files複数形の場合、ファイルフィールドの最大数Infinity
partsマルチパートフォームの場合、部品の最大数 (フィールド + ファイル)Infinity
headerPairsマルチパートフォームの場合、解析する最大ヘッダーキー=>値のペアの数2000
fieldNestingDepthMax number of nesting levels for field names (e.g. a[b][c] has 2 levels)Infinity
fieldArrayIndexLimitMax numeric array index accepted inside a field name (e.g. a[3] uses index 3)Infinity

制限を指定することは、サービス妨害(DoS)攻撃からサイトを保護するのに役立ちます。

fileFilter

どのファイルをアップロードすべきか、どの をスキップすべきかを制御する関数に設定します。 関数は次のようになります: 関数は次のようになります:

function fileFilter(req, file, cb) {
// The function should call `cb` with a boolean
// to indicate if the file should be accepted
// To reject this file pass `false`, like so:
cb(null, false);
// To accept the file pass `true`, like so:
cb(null, true);
// You can always pass an error if something goes wrong:
cb(new Error("I don't have a clue!"));
}

streamHandler

By default Multer reads the request with req.pipe(busboy). Some platforms consume the request body before your handlers run, so there is nothing left to pipe. Google Cloud Functions and Firebase Functions, for example, expose the already-read body as req.rawBody. Provide a streamHandler to feed busboy yourself in that case:

const upload = multer({
storage: multer.memoryStorage(),
streamHandler: function (req, busboy) {
if (req.rawBody) {
busboy.end(req.rawBody);
} else {
req.pipe(busboy);
}
},
});

The function receives the request and the busboy instance and must write the whole multipart body to busboy and end it.

Security

Specifying the limits can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:

  • fileSize — set to the maximum expected file size for your use case
  • files — set to the maximum number of files per request
  • fields — set to the maximum number of text fields per request
  • fieldNestingDepth — set to the minimum depth your field names require (e.g. 3 for a[b][c])
  • fieldArrayIndexLimit — set to the largest array index your field names require (e.g. 100 for a[99])

エラー処理

エラーが発生した場合、MulterはエラーをExpressに委任します。エラーが発生した場合、MulterはエラーをExpressに委任します。 You can display a nice error page using the standard express way.

Multer から特にエラーをキャッチしたい場合は、独自に ミドルウェア関数を呼び出すことができます。 Multer から特にエラーをキャッチしたい場合は、独自に ミドルウェア関数を呼び出すことができます。 Also, if you want to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError).

Multer errors carry a code (e.g. LIMIT_FILE_SIZE) and, when the error concerns a specific field, its name in field. Errors about a specific file (LIMIT_FILE_SIZE, LIMIT_UNEXPECTED_FILE) also expose the client-supplied file name in filename; treat it as untrusted input, like file.originalname.

const multer = require('multer');
const upload = multer().single('avatar');
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
}
// Everything went fine.
});
});

カスタムストレージエンジン

独自のストレージエンジンの構築方法については、Multer Storage Engineを参照してください。

ライセンス

MIT