Place an Uploaded File in a Json Object
Editor's note: This commodity was terminal updated 24 March 2022 to reflect updates to Node.js and the trunk-parser
library.
Multer is a Node.js middleware for treatment multipart/course-data
that makes the otherwise painstaking procedure of uploading files in Node.js much easier. In this article, nosotros'll learn the purpose of Multer in handling files in submitted forms. We'll besides explore Multer by edifice a mini app with a frontend and backend to test uploading a file. Let'southward get started!
Table of contents
- Managing user inputs in forms
- Encoding and uploading forms with Multer
- Multer: an overview
- Building an app with Multer back up
- Creating our frontend
- Install and configure Multer
- Conclusion
Managing user inputs in forms
Web applications receive all different types of input from users, including text, graphical controls like checkboxes or radio buttons, and files, like images, videos, and other media.
In forms, each of these inputs are submitted to a server that processes the inputs, uses them in some way, perhaps saving them somewhere else, and then gives the frontend a success
or failed
response.
When submitting forms that contain text inputs, the server, Node.js in our case, has less work to do. Using Express, you tin hands grab all the inputs entered in the req.body
object. However, submitting forms with files is a chip more complex considering they require more than processing, which is where Multer comes in.
Encoding and uploading forms with Multer
All forms include an enctype
attribute, which specifies how data should be encoded by the browser before sending it to the server. The default value is application/10-www-course-urlencoded
, which supports alphanumeric information. The other encoding blazon is multipart/form-data
, which involves uploading files through forms.
At that place are two ways to upload forms with multipart/class-data
encoding. The start is past using the enctype
aspect:
<form activity='/upload_files' enctype='multipart/form-data'> ... </form>
The code higher up sends the form-information to the /upload_files
path of your application. The second is by using the FormData
API. The FormData
API allows the states to build a multipart/class-information
class with key-value pairs that tin be sent to the server. Hither'south how it'south used:
const form = new FormData() form.append('name', "Dillion") form.append('image', <a file>)
On sending such forms, it becomes the server's responsibility to correctly parse the form and execute the final operation on the data.
Multer: an overview
Multer is a middleware designed to handle multipart/course-data
in forms. It is similar to the popular Node.js trunk-parser
, which is built into Express middleware for form submissions. Simply, Multer differs in that information technology supports multipart data, only processing multipart/form-data
forms.
Multer does the work of body-parser
past attaching the values of text fields in the req.body
object. Multer as well creates a new object for multiple files, eitherreq.file
or req.files
, which holds information almost those files. From the file object, you can pick whatever information is required to post the file to a media management API, like Cloudinary.
At present that we sympathize the importance of Multer, we'll build a minor sample app to show how a frontend app tin can send three different files at in one case in a form, and how Multer is able to process the files on the backend, making them available for further use.
Building an app with Multer support
We'll offset past building the frontend using vanilla HTML, CSS, and JavaScript. Of course, you tin easily use whatever framework to follow along.
Creating our frontend
First, create a binder called file-upload-case
, then create some other folder called frontend
inside. In the frontend folder, nosotros'll have three standard files, index.html
, styles.css
, and script.js
:
<!-- alphabetize.html --> <torso> <div course="container"> <h1>File Upload</h1> <form id='class'> <div class="input-grouping"> <label for='name'>Your proper noun</characterization> <input proper noun='proper name' id='name' placeholder="Enter your name" /> </div> <div class="input-group"> <label for='files'>Select files</label> <input id='files' type="file" multiple> </div> <button class="submit-btn" type='submit'>Upload</button> </form> </div> <script src='./script.js'></script> </body>
Notice that nosotros've created a label and input for Your Name
as well as Select Files
. We as well added an Upload
push.
Next, we'll add the CSS for styling:
/* way.css */ torso { background-color: rgb(6, 26, 27); } * { box-sizing: border-box; } .container { max-width: 500px; margin: 60px auto; } .container h1 { text-marshal: center; color: white; } form { background-color: white; padding: 30px; } form .input-group { margin-bottom: 15px; } course label { brandish: cake; margin-bottom: 10px; } class input { padding: 12px 20px; width: 100%; border: 1px solid #ccc; } .submit-btn { width: 100%; edge: none; groundwork: rgb(37, 83, iii); font-size: 18px; color: white; border-radius: 3px; padding: 20px; text-align: middle; }
Below is a screenshot of the webpage then far:

Every bit you tin see, the form we created takes 2 inputs, proper name
and files
. The multiple
attribute specified in the files
input enables united states of america to select multiple files.
Side by side, we'll send the course to the server using the code beneath:
// script.js const form = document.getElementById("form"); course.addEventListener("submit", submitForm); part submitForm(e) { e.preventDefault(); const name = certificate.getElementById("proper noun"); const files = document.getElementById("files"); const formData = new FormData(); formData.append("name", name.value); for(let i =0; i < files.files.length; i++) { formData.append("files", files.files[i]); } fetch("http://localhost:5000/upload_files", { method: 'Postal service', body: formData, headers: { "Content-Type": "multipart/form-data" } }) .then((res) => console.log(res)) .catch((err) => ("Error occured", err)); }
There are several important things that must happen when we utilize script.js
. Beginning, we become the form
element from the DOM and add a submit
event to information technology. Upon submitting, we employ preventDefault
to prevent the default action that the browser would accept when a form is submitted, which would unremarkably be redirecting to the value of the action
attribute. Next, nosotros get the name
and files
input element from the DOM and createformData.
From here, we'll append the value of the proper noun input using a key of name
to the formData
. Then, we dynamically add together the multiple files we selected to the formData
using a primal of files
.
Note: if we're just concerned with a unmarried file, we can suspend
files.files[0]
.
Finally, we'll add a Mail service
asking to http://localhost:5000/upload_files
, which is the API on the backend that nosotros'll build in the next section.
Setting upward the server
For our demo, we'll build our backend using Node.js and Express. We'll fix a simple API in upload_files
and outset our server on localhost:5000
. The API will receive a Mail
asking that contains the inputs from the submitted class.
To utilize Node.js for our server, we'll demand to set upwardly a basic Node.js projection. In the root directory of the projection in the last at file-upload-case
, run the post-obit code:
npm init -y
The command above creates a basic package.json
with some information about your app. Next, nosotros'll install the required dependency, which for our purposes is Express:
npm i express
Next, create a server.js
file and add the post-obit lawmaking:
// server.js const express = crave("express"); const app = express(); app.employ(limited.json()); app.apply(express.urlencoded({ extended: true })); app.postal service("/upload_files", uploadFiles); office uploadFiles(req, res) { panel.log(req.trunk); } app.listen(5000, () => { console.log(`Server started...`); });
Express contains the bodyParser
object, which is a middleware for populating req.body
with the submitted inputs on a form. Calling app.employ(express.json())
executes the middleware on every asking made to our server.
The API is set up with app.post('/upload_files', uploadFiles)
. uploadFiles
is the API controller. As seen above, we are only logging out req.body
, which should be populated past epxress.json()
. We'll exam this out in the example below.
Running body-parser
in Express
In your terminal, run node server
to start the server. If washed correctly, you'll run into the following in your last:

You lot tin can at present open your frontend app in your browser. Fill in both inputs in the frontend, the name and files, then click submit. On your backend, you lot should see the following:

The code in the prototype in a higher place means that the req.body
object is empty, which is to exist expected. If you'll recall, trunk-parser
doesn't back up multipart
data. Instead, we'll use Multer to parse the form.
Install and configure Multer
Install Multer by running the following command in your terminal:
npm i multer
To configure Multer, add the following to the top of server.js
:
const multer = require("multer"); const upload = multer({ dest: "uploads/" }); ...
Although Multer has many other configuration options, we're just interested in thedest
property for our project, which specifies the directory where Multer will salve the encoded files.
Next, nosotros'll utilise Multer to intercept incoming requests on our API and parse the inputs to make them bachelor on the req
object:
app.post("/upload_files", upload.assortment("files"), uploadFiles); function uploadFiles(req, res) { console.log(req.body); console.log(req.files); res.json({ message: "Successfully uploaded files" }); }
To handle multiple files, use upload.array
. For a single file, use upload.unmarried
. Note that the files
argument depends on the name of the input specified in formData
.
Multer will add the text inputs to req.body
and add together the files sent to the req.files
array. To meet this at piece of work in the terminal, enter text and select multiple images on the frontend, then submit and check the logged results in your final.
Every bit you can run across in the example below, I entered Images
in the text
input and selected a PDF, an SVG, and a JPEG file. Below is a screenshot of the logged result:

For reference, if y'all want to upload to a storage service similar Cloudinary, you will have have to send the file straight from the uploads folder. The path
property shows the path to the file.
Conclusion
For text inputs solitary, the bodyParser
object used within of Express is enough to parse those inputs. They make the inputs available as a central value pair in the req.body
object. Multer comes in handy when forms incorporate multipart
data that includes text inputs and files, which the trunk-parser
library cannot handle.
With Multer, you can handle single or multiple files in addition to text inputs sent through a course. Remember that yous should just utilise Multer when you're sending files through forms, because Multer cannot handle any form that isn't multipart.
In this article, we've seen a cursory of form submissions, the benefits of body parsers on the server and the role that Multer plays in handling form inputs. Nosotros also congenital a small application using Node.js and Multer to run across a file upload process.
For the side by side steps, you tin look at uploading to Cloudinary from your server using the Upload API Reference. I hope you enjoyed this article! Happy coding!
200'south only
Monitor failed and slow network requests in production
Deploying a Node-based web app or website is the like shooting fish in a barrel function. Making sure your Node instance continues to serve resources to your app is where things go tougher. If you're interested in ensuring requests to the backend or third political party services are successful, try LogRocket. https://logrocket.com/signup/
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you tin can amass and report on problematic network requests to rapidly understand the root cause.
LogRocket instruments your app to record baseline performance timings such as folio load time, time to outset byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.
Source: https://blog.logrocket.com/multer-nodejs-express-upload-file/
0 Response to "Place an Uploaded File in a Json Object"
Post a Comment