Professional Development

Upload a File to a Node.js Server Using React

This is a minimal example of how to upload a file to Node.js server using React.js on the front end. The Node.js server will run Express for simplicity, and takes advantage of the Express File Upload package. The server code is as simple as a single file server.js as follows:

const express = require('express');
const fileUpload = require('express-fileupload');

const app = express();

// upload Endpoint'/upload', (req, res) => {
  if (!req.filesnull) {
    return res.status(400).json({ msg: 'No file uploaded' });

  const file = req.files.file;`../client/public/uploads/${}`, err => {
    if (err) {
      return res.status(500).send(err);
    res.json({ fileName:, filePath: `/uploads/${}` });

app.listen(5000, () => console.log('Server Started...'));

This will load a file POST’d to /upload in the folder path relative to where this file resides. Update the path to an existing directory location, or you’ll get a 500 response.

On the front end, we have a simple React component that looks like:

import React from 'react';
import axios from 'axios';

const FileUpload = () => {

  const onChange = async e => {
    const formData = new FormData(); 
    for (var pair of formData.entries()) {
    try {
      await'/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'

    } catch (err) {

  return (
      <input type='file' onChange={onChange} />

export default FileUpload;

The file is uploaded after it is selected, no need for submitting a form.

Full project is available here:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s