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();
app.use(fileUpload());

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

  const file = req.files.file;

  file.mv(`../client/public/uploads/${file.name}`, err => {
    if (err) {
      console.error(err);
      return res.status(500).send(err);
    }
    res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
  });
});

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(); 
    formData.append('file', e.target.files[0]);
    for (var pair of formData.entries()) {
        console.log(pair[1]); 
      }
    try {
      await axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

    } catch (err) {
      console.log(err);
    }
  };

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

export default FileUpload;

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

Full project is available here: https://github.com/dikuw/fileupload

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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