Upload Files to Server Using JavaScript

Upload Files to Server Using JavaScript

In this tutorial, you will learn how to upload files to the server using JavaScript.

One of the most popular files handling features in a web app is the ability to upload a file to a server and process it in the backend. Consider uploading an avatar or an attachment.

Uploading Files From Client To Server Using JavaScript Example

Consider a file input element for HTML:

<input type="file" id="fileUpload" />

When the user selects an image, we activate the handleImageUpload() function and pass in the file they choose by registering a change handler on the #fileUpload DOM element.

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)
})

To deliver the file to the server, we use the Fetch API. When the server returns properly, the image path will be sent to us in the path attribute.

We'll perform what we need to do with that, such as updating the interface with the image.

Handling the file upload server-side using Node.js

The server component is described further down. To handle the request, I'm using Node.js and the Express framework.

Install the npm module express-fileupload:

npm install express-fileupload

and incorporate it into your middleware:

import fileupload from 'express-fileupload'

//or

const fileupload = require('express-fileupload')

After you created your Express app, add:

app.use(
		fileupload(),
    //...

This is required because otherwise, the server will be unable to parse file uploads.

Uploaded files are now available in req.files. If you don't include that middleware, req.files will be undefined.

app.post('/saveImage', (req, res) => {
  const fileName = req.files.myFile.name
  const path = __dirname + '/images/' + fileName

  image.mv(path, (error) => {
    if (error) {
      console.error(error)
      res.writeHead(500, {
        'Content-Type': 'application/json'
      })
      res.end(JSON.stringify({ status: 'error', message: error }))
      return
    }

    res.writeHead(200, {
      'Content-Type': 'application/json'
    })
    res.end(JSON.stringify({ status: 'success', path: '/img/houses/' + fileName }))
  })
})

You can consider this the bare minimum of code needed to manage files.

The uploaded image's mv attribute is referred to as. The express-fileupload module provides us with this. We move it to the path and then announce the success (or failure!) to the client.

Check the properties of the files uploaded client-side

In the handleImageUpload function, you can perform any necessary preprocessing, such as checking the file type or size:

const handleImageUpload = event => {
  const files = event.target.files
  const myImage = files[0]
  const imageType = /image.*/

  if (!myImage.type.match(imageType)) {
    alert('Only image upload is allowed.')
    return
  }

  if (myImage.size > (100*1024)) {
    alert('The maximum file size allowed is 100KB.')
    return
  }

  //...
}