How to Upload Files to the Server Using JavaScript
Uploading files and processing them in the backend is a common functionality in web applications, such as uploading avatars or attachments. In this article, we will learn how to upload files to the server using JavaScript.
Uploading Files Client-Side
To enable file upload functionality in our web app, we start by adding an HTML file input element:
1 | <input type="file" id="fileUpload" /> |
Next, we register a change handler on the #fileUpload
DOM element. When the user selects a file, we trigger the handleImageUpload()
function and pass in the selected file.
1 | const handleImageUpload = event => { |
We use the Fetch API to send the file to the server. Once the server successfully processes the file, it will return the image path in the path
property of the response. This allows us to update the interface as needed.
Handling File Upload Server-Side with Node.js
Now let’s look at the server-side implementation using Node.js with the Express framework.
First, install the express-fileupload
npm module:
1 | npm install express-fileupload |
Then, add it to your middleware:
1 | const fileupload = require('express-fileupload'); |
Adding this middleware allows the server to parse file uploads properly. Otherwise, the req.files
object will be undefined
.
To handle file uploads, define a route for handling the /saveImage
endpoint:
1 | app.post('/saveImage', (req, res) => { |
In this example, we use the mv
property of the uploaded file, which is provided by the express-fileupload
module, to move the file to the desired path. Then, we communicate either the success or an error back to the client.
Checking File Properties Client-Side
If you need to check the file type or size before uploading it, you can preprocess them in the handleImageUpload
function. Here’s an example that checks if the file is an image and its size is within the allowed limit:
1 | const handleImageUpload = event => { |
By using these techniques, you can implement file upload functionality in your web app and handle the files both on the client and server side with ease.
tags: [“file upload”, “JavaScript”, “Node.js”, “Express”, “backend development”]