X

Node.js

Uploading Files using Multer & Express

June 25, 2021

/*

Uploading Files using Multer & Express

*/

Multer is a package that makes uploading images, pdfs & other big files easier. To start, we need to run a function called multer. This function takes an options object, this object has a destination property. This property takes a path to where you want the uploaded files to be stored. The multer function will return an object which has methods that will upload the files.

<code-div></code-div>

/*

Using Upload.single to upload files

*/

The upload.single() takes 1 argument that is the name attribute of the file input you want to upload. You'll use this method as middleware to upload the file. When this method runs the file will be uploaded in the destination property that you made in the multer function.

<code-div></code-div>

/*

Using Upload.array to upload multiple files

*/

The upload.array() takes 2 arguments, the first one is the same as the upload.single() method, the second is the max number of files you can upload at a time.

<code-div></code-div>

/*

The req.file object

*/

When you use the multer function it appends a file object to the request object. This object tells us the details of the file being uploaded. When uploading multiple files it turns into req.files.

<code-div></code-div>

/*

Configuring index.html to send files

*/

When you use multer you have to make sure the html form attribute enctype is set to multipart/form-data & the input file's name is the same name in the upload.single method. Also if your using uploading multiple files you have to use the multiple attribute in the file input.

<code-div></code-div>


/*

Final Result

*/

The final result can be found here Upload File with Multer.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.