React JS+ Node JS File Upload Example

React JS+ Node JS File Upload Example

React js + Node js Express file/image upload with form data example. In this tutorial, you will learn how to upload file/image in react js app with node express js.

For the backend, this tutorial will use a simple node express js application that exposes a unique endpoint that accepts a POST request containing the file/image to upload.

Before start this react js + node express js file upload tutorial; you’ll need to have Node.js installed which can be done by following the instructions on this tutorial.

React + Node JS + Express JS File Upload

  • Create React Frontend App
    • Step 1 – Create React App
    • Step 2 – Install Axios and Bootstrap 4
    • Step 3 – Create File Upload Form Component
    • Step 4 – Import Component in App.js
  • Create Node Express JS Backend
    • Step 1 – Create Node JS App
    • Step 2 – Install Express body parser and cors Dependencies
    • Step 3 – Create Server.js
    • Step 4 – Start Node JS App

Create React Frontend App

Step 1 – Create React App

Open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Axios and Bootstrap 4

Then execute the following command to install axios and boostrap 4 library into your react app:

npm install bootstrap --save

npm install axios --save

Add bootstrap.min.css file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div>
      <h2>react node js file upload example</h2>
    </div>
  );
}

export default App;

Step 3 – Create File Upload Form Component

In this step, visit src directory of your react js app and create a form component named FileUpload.js. And add the following code into it:

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

class FileUpload extends React.Component{

      const [file, setFile] = useState();
      const [fileName, setFileName] = useState("");

      const saveFile = (e) => {
        setFile(e.target.files[0]);
        setFileName(e.target.files[0].name);
      };

      const uploadFile = async (e) => {
        const formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", fileName);
        try {
          const res = await axios.post(
            "http://localhost:3000/upload",
            formData
          );
          console.log(res);
        } catch (ex) {
          console.log(ex);
        }
      };

    render(){
      return (
        <div className="App">
          <input type="file" onChange={saveFile} />
          <button onClick={uploadFile}>Upload</button>
        </div>
      );
    }
}

export default FileUpload;

Step 4 – Import Component in App.js

In this step, you need to add FileUpload.js file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import FileUpload from './FileUpload'

function App() {  
    
  return (  
    <div className="App">  
      <FileUpload/>  
    </div>  
  );  
}  

export default App;

Create Node Express JS Backend

Step 1 – Create Node JS App

Open your terminal and execute the following command to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Install Express body parser and cors Dependencies

Execute the following commands to install imperative npm packages which will help us to create REST APIs for your react file upload app:

npm install express cors body-parser express-fileupload
npm install nodemon --save-dev

Step 3 – Create Server.js File

In this step, create server.js file and add the following code into it:

const express = require("express");
const fileupload = require("express-fileupload");
const cors = require("cors");
const bodyParser = require('body-parser');

const app = express();

app.use(cors());
app.use(fileupload());
app.use(express.static("files"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/upload", (req, res) => {
  const newpath = __dirname + "/files/";
  const file = req.files.file;
  const filename = file.name;

  file.mv(`${newpath}${filename}`, (err) => {
    if (err) {
      res.status(500).send({ message: "File upload failed", code: 200 });
    }
    res.status(200).send({ message: "File Uploaded", code: 200 });
  });
});

app.listen(3000, () => {
  console.log("Server running successfully on 3000");
});

Step 4 – Start Node JS App

Start the server with the following command and then you can test the form:

npm start

OR

nodemon server.js

Conclusion

React js + node express js file upload example tutorial; you have learned how to upload file in react js app using node js express rest api.

Recommended React JS + Node Express JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

2 replies to React JS+ Node JS File Upload Example

  1. Amazing write up! From this tutorial i learned how to upload file/image in react js app with node express js. This is so informative article for the beginners like me. My appreciation to you!

  2. Thank you so much, it helped me

Leave a Reply

Your email address will not be published. Required fields are marked *