Join the 2022 Full-Stack Web Dev Bootcamp!
Uploading a file and process it in the backend in one of the most common file handling functionalities in a web app: think about uploading an avatar or an attachment.
Say we have an HTML file input element:
We register a change handler on the #fileUpload DOM element, and when the user chooses an image, we trigger the handleImageUpload() function passing in the file selected.
We use the Fetch API to send the file to the server. When the server returns successfully, it will send us the image path in the path property.
With that, we will do what we need to do, like updating the interface with the image.
Handling the file upload server-side using Node.js
The server part is detailed here below. Im using Node.js with the Express framework to handle the request.
Install the express-fileupload npm module:
and add it to your middleware:
After you created your Express app, add:
This is needed because otherwise the server cant parse file uploads.
Now uploaded files are provided in req.files. If you forget to add that middleware, req.files would be undefined.
This is the smallest amount of code needed to handle files.
We call the mv property of the uploaded image. That is provided to us by the express-fileupload module. We move it to path and then we communicate the success (or an error!) back to the client.
Check the properties of the files uploaded client-side
If you need to check the filetype or the file size, you can preprocess them in the handleImageUpload function, like this:
Download my free JavaScript Beginner's Handbook!
Want to become a better Web Developer? Join the 2022 Web Development Bootcamp!