Gathering detailed insights and metrics for fastify-multer
Gathering detailed insights and metrics for fastify-multer
Gathering detailed insights and metrics for fastify-multer
Gathering detailed insights and metrics for fastify-multer
fastify-file-interceptor
This library for Nestjs using FastifyAdapter it rely on library fastify-multer and express multer
nest-fastify-multer
The objective of this module is to provide a package with filters already prepared to work with 'fastify-multer'.
@nest-lab/fastify-multer
A File Upload package for NestJS when using fastify
multer
Middleware for handling `multipart/form-data`.
npm install fastify-multer
97.1
Supply Chain
98.7
Quality
74.6
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
89 Stars
344 Commits
14 Forks
3 Watching
2 Branches
38 Contributors
Updated on 21 Aug 2024
Minified
Minified + Gzipped
TypeScript (99.89%)
JavaScript (0.11%)
Cumulative downloads
Total Downloads
Last day
19.8%
11,054
Compared to previous day
Last week
26.6%
52,819
Compared to previous week
Last month
10.9%
191,819
Compared to previous month
Last year
98.9%
2,308,860
Compared to previous year
This package is a port to Fastify of express multer.
Multer is a Fastify plugin for handling multipart/form-data
, which is primarily used for uploading files. It is written
on top of busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data
).
fastify-multer 2.x.x version supports Fastify >= 3.0.0. For Fastify < 3.0.0 use fastify-multer 1.x.x version
1$ npm install --save fastify-multer
Multer adds a body
object and a file
or files
object to the Fastify's 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.
Basic usage example:
Don't forget the enctype="multipart/form-data"
in your form.
1<form action="/profile" method="post" enctype="multipart/form-data"> 2 <input type="file" name="avatar" /> 3</form>
1const fastify = require('fastify') // or import fastify from 'fastify' 2const multer = require('fastify-multer') // or import multer from 'fastify-multer' 3const upload = multer({ dest: 'uploads/' }) 4 5const server = fastify() 6// register fastify content parser 7server.register(multer.contentParser) 8 9server.route({ 10 method: 'POST', 11 url: '/profile', 12 preHandler: upload.single('avatar'), 13 handler: function(request, reply) { 14 // request.file is the `avatar` file 15 // request.body will hold the text fields, if there were any 16 reply.code(200).send('SUCCESS') 17 } 18}) 19 20// or using the short hand declaration 21server.post( 22 '/profile', 23 { preHandler: upload.single('avatar') }, 24 function(request, reply) { 25 // request.file is the `avatar` file 26 // request.body will hold the text fields, if there were any 27 reply.code(200).send('SUCCESS') 28 } 29) 30 31server.route({ 32 method: 'POST', 33 url: '/photos/upload', 34 preHandler: upload.array('photos', 12), 35 handler: function(request, reply) { 36 // request.files is array of `photos` files 37 // request.body will contain the text fields, if there were any 38 reply.code(200).send('SUCCESS') 39 } 40}) 41 42const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) 43server.route({ 44 method: 'POST', 45 url: '/cool-profile', 46 preHandler: cpUpload, 47 handler: function(request, reply) { 48 // request.files is an object (String -> Array) where fieldname is the key, and the value is array of files 49 // 50 // e.g. 51 // request.files['avatar'][0] -> File 52 // request.files['gallery'] -> Array 53 // 54 // request.body will contain the text fields, if there were any 55 reply.code(200).send('SUCCESS') 56 } 57})
In case you need to handle a text-only multipart form, you should use the .none()
method:
1const fastify = require('fastify') 2const multer = require('fastify-multer') 3const server = fastify() 4const upload = multer() 5 6server.route({ 7 method: 'POST', 8 url: '/profile', 9 preHandler: upload.none(), 10 handler: function(request, reply) { 11 // request.body contains the text fields 12 reply.code(200).send('SUCCESS') 13 } 14})
Each file contains the following information:
Key | Description | Note |
---|---|---|
fieldname | Field name specified in the form | |
originalname | 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 | |
destination | The folder to which the file has been saved | DiskStorage |
filename | The name of the file within the destination | DiskStorage |
path | The full path to the uploaded file | DiskStorage |
buffer | A Buffer of the entire file | MemoryStorage |
multer(opts)
Multer accepts an options object, the most basic of which is the dest
property, which tells Multer where to upload the files. In case you omit the
options object, the files will be kept in memory and never written to disk.
By default, Multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs.
The following are the options that can be passed to Multer.
Key | Description |
---|---|
dest or storage | Where to store the files |
fileFilter | Function to control which files are accepted |
limits | Limits of the uploaded data |
preservePath | Keep the full path of files instead of just the base name |
In an average web app, only dest
might be required, and configured as shown in
the following example.
1const upload = multer({ dest: 'uploads/' })
If you want more control over your uploads, you'll want to use the storage
option instead of dest
. Multer ships with storage engines DiskStorage
and MemoryStorage
; More engines are available from third parties.
.single(fieldname)
Accept a single file with the name fieldname
. The single file will be stored
in request.file
.
.array(fieldname[, maxCount])
Accept an array of files, all with the name fieldname
. Optionally error out if
more than maxCount
files are uploaded. The array of files will be stored in
request.files
.
.fields(fields)
Accept a mix of files, specified by fields
. An object with arrays of files
will be stored in request.files
.
fields
should be an array of objects with name
and optionally a maxCount
.
Example:
1[ 2 { name: 'avatar', maxCount: 1 }, 3 { name: 'gallery', maxCount: 8 } 4]
.none()
Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.
.any()
Accepts all files that comes over the wire. An array of files will be stored in
request.files
.
WARNING: Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files.
storage
DiskStorage
The disk storage engine gives you full control on storing files to disk.
1const storage = multer.diskStorage({ 2 destination: function (req, file, cb) { 3 cb(null, '/tmp/my-uploads') 4 }, 5 filename: function (req, file, cb) { 6 cb(null, file.fieldname + '-' + Date.now()) 7 } 8}) 9 10const upload = multer({ storage: storage })
There are two options available, destination
and filename
. They are both
functions that determine where the file should be stored.
destination
is used to determine within which folder the uploaded files should
be stored. This can also be given as a string
(e.g. '/tmp/uploads'
). If no
destination
is given, the operating system's default directory for temporary
files is used.
Note: You are responsible for creating the directory when providing
destination
as a function. When passing a string, multer will make sure that
the directory is created for you.
filename
is used to determine what the file should be named inside the folder.
If no filename
is given, each file will be given a random name that doesn't
include any file extension.
Note: Multer will not append any file extension for you, your function should return a filename complete with an file extension.
Each function gets passed both the Fastify's request (request
) and some information about
the file (file
) to aid with the decision.
Note that request.body
might not have been fully populated yet. It depends on the
order that the client transmits fields and files to the server.
MemoryStorage
The memory storage engine stores the files in memory as Buffer
objects. It
doesn't have any options.
1const storage = multer.memoryStorage() 2const upload = multer({ storage: storage })
When using memory storage, the file info will contain a field called
buffer
that contains the entire file.
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.
The following integer values are available:
Key | Description | Default |
---|---|---|
fieldNameSize | Max field name size | 100 bytes |
fieldSize | Max field value size | 1MB |
fields | Max number of non-file fields | Infinity |
fileSize | For multipart forms, the max file size (in bytes) | Infinity |
files | For multipart forms, the max number of file fields | Infinity |
parts | For multipart forms, the max number of parts (fields + files) | Infinity |
headerPairs | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
fileFilter
Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:
1function fileFilter (request, file, cb) { 2 3 // The function should call `cb` with a boolean 4 // to indicate if the file should be accepted 5 6 // To reject this file pass `false`, like so: 7 cb(null, false) 8 9 // To accept the file pass `true`, like so: 10 cb(null, true) 11 12 // You can always pass an error if something goes wrong: 13 cb(new Error('I don\'t have a clue!')) 14 15}
When encountering an error, Multer will delegate the error to Fastify. You can display a nice error page using the standard fastify way.
If you want to catch errors specifically from Multer, you can call the
middleware function by yourself. 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
).
For information on how to build your own storage engine, see Multer Storage Engine.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 5/21 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More