Uploading Image File and Storing It in an Array Javascript
Multer
Multer is a node.js middleware for handling multipart/course-data
, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
Annotation: Multer will non process any form which is not multipart (multipart/form-data
).
Translations
This README is also available in other languages:
- Español (Spanish)
- 简体中文 (Chinese)
- 한국어 (Korean)
- Русский язык (Russian)
- Việt Nam (Vietnam)
- Português (Portuguese Brazil)
Installation
$ npm install --save multer
Usage
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.
Basic usage example:
Don't forget the enctype="multipart/form-data"
in your class.
< form activity="/profile" method="mail service" enctype="multipart/grade-data"> < input type="file" name="avatar" /> </ class >
const limited = require ( 'express' ) const multer = require ( 'multer' ) const upload = multer ( { dest: 'uploads/' } ) const app = limited ( ) app . postal service ( '/contour' , upload . single ( 'avatar' ) , function ( req , res , next ) { // req.file is the `avatar` file // req.torso will hold the text fields, if in that location were whatsoever } ) app . mail service ( '/photos/upload' , upload . array ( 'photos' , 12 ) , office ( req , res , adjacent ) { // req.files is array of `photos` files // req.torso will contain the text fields, if there were any } ) const cpUpload = upload . fields ( [ { proper noun: 'avatar' , maxCount: 1 } , { name: 'gallery' , maxCount: 8 } ] ) app . post ( '/cool-profile' , cpUpload , part ( 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'] -> Assortment // // req.body will contain the text fields, if in that location were whatsoever } )
In example you need to handle a text-only multipart course, y'all should use the .none()
method:
const express = require ( 'express' ) const app = express ( ) const multer = require ( 'multer' ) const upload = multer ( ) app . postal service ( '/profile' , upload . none ( ) , function ( req , res , adjacent ) { // req.body contains the text fields } )
Hither's an example on how multer is used an HTML class. Take special notation of the enctype="multipart/form-data"
and name="uploaded_file"
fields:
< form action="/stats" enctype="multipart/form-data" method="postal service"> < div class="form-group"> < input type="file" grade="form-command-file" proper noun="uploaded_file"> < input blazon="text" class="form-control" placeholder="Number of speakers" proper name="nspeakers"> < input type="submit" value="Get me the stats!" class="btn btn-default"> </ div > </ form >
Then in your javascript file yous would add these lines to access both the file and the body. Information technology is important that you use the name
field value from the grade in your upload part. This tells multer which field on the request it should expect for the files in. If these fields aren't the aforementioned in the HTML grade and on your server, your upload volition fail:
const multer = require ( 'multer' ) const upload = multer ( { dest: './public/information/uploads/' } ) app . mail service ( '/stats' , upload . single ( 'uploaded_file' ) , function ( req , res ) { // req.file is the name of your file in the course above, here 'uploaded_file' // req.body volition concur the text fields, if there were any panel . log ( req . file , req . body ) } ) ;
API
File information
Each file contains the following information:
Key | Description | Annotation |
---|---|---|
fieldname | Field proper name specified in the form | |
originalname | Name of the file on the user'southward 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 proper name of the file inside the destination | DiskStorage |
path | The full path to the uploaded file | DiskStorage |
buffer | A Buffer of the unabridged file | MemoryStorage |
multer(opts)
Multer accepts an options object, the well-nigh basic of which is the dest
holding, which tells Multer where to upload the files. In case y'all omit the options object, the files will be kept in retentiveness and never written to disk.
By default, Multer volition rename the files and then equally 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.
Fundamental | Description |
---|---|
dest or storage | Where to store the files |
fileFilter | Function to control which files are accepted |
limits | Limits of the uploaded data |
preservePath | Proceed the full path of files instead of just the base proper name |
In an average web app, only dest
might be required, and configured as shown in the following example.
const 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 unmarried file with the name fieldname
. The single file volition be stored in req.file
.
.assortment(fieldname[, maxCount])
Have an assortment of files, all with the name fieldname
. Optionally error out if more maxCount
files are uploaded. The array of files will be stored in req.files
.
.fields(fields)
Accept a mix of files, specified past fields
. An object with arrays of files will exist stored in req.files
.
fields
should be an array of objects with proper noun
and optionally a maxCount
. Example:
[ { name: 'avatar' , maxCount: 1 } , { name: 'gallery' , maxCount: 8 } ]
.none()
Have but 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 assortment of files will be stored in req.files
.
WARNING: Make sure that you ever handle the files that a user uploads. Never add multer every bit a global middleware since a malicious user could upload files to a route that you didn't conceptualize. Only utilize this function on routes where you are treatment the uploaded files.
storage
DiskStorage
The disk storage engine gives you full control on storing files to disk.
const storage = multer . diskStorage ( { destination: function ( req , file , cb ) { cb ( null , '/tmp/my-uploads' ) } , filename: function ( req , file , cb ) { const uniqueSuffix = Appointment . now ( ) + '-' + Math . round ( Math . random ( ) * 1E9 ) cb ( null , file . fieldname + '-' + uniqueSuffix ) } } ) const upload = multer ( { storage: storage } )
There are ii 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 exist stored. This tin can also be given as a string
(eastward.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 certain that the directory is created for yous.
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 volition not append whatsoever file extension for yous, your function should return a filename complete with an file extension.
Each function gets passed both the request (req
) and some information about the file (file
) to aid with the conclusion.
Annotation that req.body
might not have been fully populated withal. It depends on the club that the client transmits fields and files to the server.
For understanding the calling convention used in the callback (needing to pass null as the starting time param), refer to Node.js fault treatment
MemoryStorage
The memory storage engine stores the files in retentivity as Buffer
objects. It doesn't have any options.
const storage = multer . memoryStorage ( ) const upload = multer ( { storage: storage } )
When using retentivity storage, the file info volition incorporate a field called buffer
that contains the entire file.
Warning: Uploading very big files, or relatively small files in large numbers very quickly, tin crusade your application to run out of memory when memory storage is used.
limits
An object specifying the size limits of the post-obit optional properties. Multer passes this object into busboy directly, and the details of the properties tin can be found on busboy's page.
The post-obit integer values are available:
Key | Description | Default |
---|---|---|
fieldNameSize | Max field name size | 100 bytes |
fieldSize | Max field value size (in bytes) | 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 central=>value pairs to parse | 2000 |
Specifying the limits tin assist protect your site against deprival of service (DoS) attacks.
fileFilter
Fix this to a function to control which files should be uploaded and which should be skipped. The part should look like this:
function fileFilter ( req , file , cb ) { // The function should call `cb` with a boolean // to point if the file should exist accepted // To turn down this file laissez passer `false`, like so: cb ( zippo , faux ) // To accept the file pass `truthful`, similar then: cb ( zip , true ) // You lot can always laissez passer an error if something goes wrong: cb ( new Error ( 'I don\'t have a clue!' ) ) }
Mistake handling
When encountering an error, Multer volition delegate the error to Express. Yous can display a nice error page using the standard limited way.
If y'all want to catch errors specifically from Multer, you tin call the middleware function past yourself. Also, if you want to catch merely the Multer errors, you tin can use the MulterError
form that is attached to the multer
object itself (east.thou. err instanceof multer.MulterError
).
const multer = require ( 'multer' ) const upload = multer ( ) . unmarried ( '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. } ) } )
Custom storage engine
For information on how to build your own storage engine, see Multer Storage Engine.
License
MIT
andersonagook1988.blogspot.com
Source: https://www.npmjs.com/package/multer
0 Response to "Uploading Image File and Storing It in an Array Javascript"
Post a Comment