DEV Community 👩‍💻👨‍💻

Cover image for React+Express Tutorial - How to Uploads Image & File Using ReactJs and experss-fileupload
Abdul Waqar
Abdul Waqar

Posted on

React+Express Tutorial - How to Uploads Image & File Using ReactJs and experss-fileupload

How we can upload a file with Reactjs App using expressjs and express-fileupload?

In this tutorial we will learn how we can set up expressjs Server and React Application to upload images and then save that image in a folder.

You need basic knowledge of :

  • ReactJS for the frontend
  • expressjs for backend.

I have divided this tutorial into two parts. In part 1 we will set up express server which will accept image and save it in a folder. And in part 2, We will create React Application and by using axios we will send image data to our API endpoint.

Part : 01

Let's set up our express server which will provide an API endpoint and accept images as parameter then save for later use.

  1. Make an empty directory "react-express-fileupload"
  2. Create a packege.json file

Type the following command in the terminal :

npm init -y

This command will create a package.json file with default options in your root directory.

  1. Install required dependencies.

npm i express express-fileupload

This command will install express and express-fileupload these are libraries that we will use in our application. Express is an application framework for the backend and express-fileupload is used to accept a file as a parameter and save it at some location.

  1. Install Dev dependency (Optional)

npm i nodemon concurrently -D

nodemon is used to restart our application when we are working in development mode. concurrently is used to run multiple scripts with a single command in our application we need two servers one for the backend and the second for React Application. Using concurrently we will run both servers at the same time.

  1. Create a server.js file in the root directory. In this file, we will write our code that will provide an endpoint and accepts a file as a parameter. Use the following code in server.js file :
const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();
app.use(fileUpload());
// Upload Endpoint That will accept files
app.post("/upload", (req, res) => {
  // Check if file is not available return message with status 400.
  if (req.files === null) {
    return res.status(400).json({ msg: "No file uploaded" });
  }
  const file = req.files.file;
  // We need unique file name to save it in folder and then use filename to access it. I have replace space with - and concatinated file name with Date String. We can also used uuid package as well.
  const UFileName = `${new Date().getTime()}-${file.name.replaceAll(" ", "-")}`;
  // This line of code will save our file in public/uploads folder in our
  //appliction and will retrun err if any error found if no error found then return pathname of file.
  file.mv(`${__dirname}/client/public/uploads/${UFileName}`, (err) => {
    if (err) {
      console.error(err);
      return res.status(500).send(err);
    }
    res.json({ fileName: UFileName, filePath: `/uploads/${UFileName}` });
  });
});
// Create an express server which will listen requests at port 5000
app.listen(5000, () => console.log("Server Started..."));
Enter fullscreen mode Exit fullscreen mode
  1. Now Updated script in packege.json file to run our server.js file.
"scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
  }
Enter fullscreen mode Exit fullscreen mode
  1. Create React application by running create-react-app client in root folder and create uploads folder in the public directory of client application.

After the creation of React application starts our application with npm run dev command. Now we can test our Endpoint using postman.

When we test application we will get filename and pathname in response.

React File & Image Upload

Part: 2

In this section we will upload our code of client application which we created using create-react-app 1. Create A from where we will submit our file.

// Import axios to post Request
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8tr3zu08jp8ycy413x8u.png)
import axios form 'axios'
// Create State for variables
 const [file, setFile] = useState("");
  const [filename, setFilename] = useState("Choose File");
  const [uploadedFile, setUploadedFile] = useState({});
  const [message, setMessage] = useState("");
 // Create OnSubmit function
 const onSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("file", file);
    try {
      const res = await axios.post("/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      const { fileName, filePath } = res.data;
      setUploadedFile({ fileName, filePath });
      setMessage("File Uploaded");
    } catch (err) {
      if (err.response.status === 500) {
        setMessage("There was a problem with the server");
      } else {
        setMessage(err.response.data.msg);
      }

    }
  };
  // Create OnChange Event for Input Box
 const onChange = (e) => {
    setFile(e.target.files[0]);
    setFilename(e.target.files[0].name);
  };
//Form Code
<form onSubmit={onSubmit}>
  <div className="custom-file mb-4">
    <input
      type="file"
      className="custom-file-input"
      id="customFile"
      onChange={onChange}
      required
    />
    <label className="custom-file-label" htmlFor="customFile">
      {filename}
    </label>
  </div>

  <input
    type="submit"
    value="Upload"
    className="btn btn-primary btn-block mt-4"
  />
</form>
// Display message using Conditional Statement
  {message ? <p> msg={message} </p> : null}
  //Display Uploaded File on Web pages
  {uploadedFile ? (
        <div className="row mt-5">
          <div className="col-md-6 m-auto">
            <h3 className="text-center">{uploadedFile.fileName}</h3>
            <img style={{ width: "100%" }} src={uploadedFile.filePath} alt="" />
          </div>
        </div>
      ) : null}

Enter fullscreen mode Exit fullscreen mode

From here, you should be able to build complete application (Fronend+Backend ) and test as we have

From here, you should be able to build the complete application (Fronend+Backend ) and test as we have done in the previous steps.

The code for this project is located Here

I am Abdul Waqar

A Fullstack Developer with Experience of More than 3 Years.
I am available at :

I am at:

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.