How to upload files to the server using JavaScript
By Flavio Copes
Learn how to upload files to the server with JavaScript using FormData and the Fetch API, then handle them in Node.js and Express with express-fileupload.
Uploading a file and processing it in the backend is 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:
<input type="file" id="fileUpload" />
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.
const handleImageUpload = event => {
const files = event.target.files
const formData = new FormData()
formData.append('myFile', files[0])
fetch('/saveImage', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data.path)
})
.catch(error => {
console.error(error)
})
}
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event)
})
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. I’m using Node.js with the Express framework to handle the request.
Install Express and the express-fileupload npm module:
npm install express express-fileupload
This installs Express 5, the current major version. It needs Node.js 18 or later, and the code in this post works with it.
Then import the module:
import fileupload from 'express-fileupload'
//or
const fileupload = require('express-fileupload')
After you created your Express app, add:
app.use(fileupload())
This is needed because otherwise the server can’t parse file uploads.
Now uploaded files are provided in req.files. Each file uses the name we passed to formData.append(), so our file is req.files.myFile.
If you forget to add that middleware, req.files is undefined. It’s also undefined when a request comes in without a file, so we check for it first:
app.post('/saveImage', (req, res) => {
if (!req.files || !req.files.myFile) {
res.status(400).json({ status: 'error', message: 'No file uploaded' })
return
}
const file = req.files.myFile
const path = __dirname + '/images/' + file.name
file.mv(path, (error) => {
if (error) {
console.error(error)
res.status(500).json({ status: 'error', message: error.message })
return
}
res.json({ status: 'success', path: '/images/' + file.name })
})
})
This is the smallest amount of code needed to handle files.
We call the mv() method of the uploaded file. That is provided to us by the express-fileupload module. We move the file to path and then we communicate the success (or an error!) back to the client.
The images folder must already exist, otherwise mv() fails with an ENOENT error. If you want the module to create it for you, pass fileupload({ createParentPath: true }).
__dirname works in CommonJS files, the ones using require(). In an ES module, use import.meta.dirname instead. It’s available since Node.js 20.11.
A production app also needs size limits, file type checks, and generated filenames instead of the one the user sent. I cover those in File uploads in Node.js with Express.
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:
const handleImageUpload = event => {
const files = event.target.files
const myImage = files[0]
const imageType = /image.*/
if (!myImage.type.match(imageType)) {
alert('Sorry, only images are allowed')
return
}
if (myImage.size > (100*1024)) {
alert('Sorry, the max allowed size for images is 100KB')
return
}
//...
}Want me to talk about your product? You can sponsor this site.
Related posts about js: