Skip to main content

Learn React File Upload In 5 Minute

This tutorial help to create file upload into react application. We will demonstrate step by step process to react file upload.

We will use nodejs API to file upload into the server. The react application will use to upload files to the client-side and send files to the node API server.

React Upload File in React

Let’s integrate react file upload component into our react application. We will use nodejs application to upload file to the server. Create Nodejs API to Upload file Using Multer example use to upload file into the server.

We will use the following dependencies in this project –

  • Bootstrap 4 : We will use bootstrap for UI.
  • ReactToastify: These libs are used to display alert notifications.
  • axios : Promise based HTTP client for the browser and node.js

Checkout Other tutorials:

How To Create React App

Let’s create react app using the command line. The following command will create react scratch app –
npx create-react-app react-file-upload

We will cd into react project react-file-upload
cd react-file-upload

Now will install dependencies –

npm install bootstrap
npm install react-toastify
npm install axios

The bootstrap help to create UI based on bootstrap 4, react-toastify is used to display beautiful notification into react app and axios for HTTP client.

Now run the application.
npm start

You can see react home page in the browser https://localhost:3000 .

Let’s create a file upload component for this application.

Create File Upload UI

I have taken reference from bootsnipp for UI, let’s add HTML into app.js file.

onChangeHandler=event=>{
    var file = event.target.files[0];
    console.log(file);
    console.log(this.validateSize(event));
    if(this.validateSize(event)){ 
      console.log(file);
  // if return true allow to setState
     this.setState({
      selectedFile: file
      });

    }
  }
  fileUploadHandler = () => {
    const data = new FormData()
    console.log(this.state.selectedFile);
    data.append('file', this.state.selectedFile)
    console.log(data);
    axios.post("https://localhost:8010/api/v1/upload", data)
      .then(res => { // then print response status
        toast.success('upload success')
      })
      .catch(err => { // then print response status
        toast.error('upload fail')
      })

  };
  validateSize=(event)=>{
  let file = event.target.files[0];
  let size = 30000;
  let err = '';
  console.log(file.size);
  if (file.size > size) {
   err = file.type+'is too large, please pick a smaller file\n';
   toast.error(err);
 }
 return true
};

Above HTML code, Added ToastContainer component to display notification.Created file input field to take user input and submit button for send request to the server.

Added onchange event into the input field and associated method onChangeHandler to set file information into the state.

The fileUploadHandler method associated with submit onclick event. This method sends a request to nodejs server using Axios HTTP client.

Now added upload form CSS styling into app.css file –

.files input {
    outline: 2px dashed #92b0b3;
    outline-offset: -10px;
    -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
    transition: outline-offset .15s ease-in-out, background-color .15s linear;
    padding: 120px 0px 85px 35%;
    text-align: center !important;
    margin: 0;
    width: 100% !important;
}
.files input:focus{     outline: 2px dashed #92b0b3;  outline-offset: -10px;
    -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
    transition: outline-offset .15s ease-in-out, background-color .15s linear; border:1px solid #92b0b3;
 }
.files{ position:relative}
.files:after {  pointer-events: none;
    position: absolute;
    top: 60px;
    left: 0;
    width: 50px;
    right: 0;
    height: 56px;
    content: "";
    background-image: url(https://image.flaticon.com/icons/png/128/109/109612.png);
    display: block;
    margin: 0 auto;
    background-size: 100%;
    background-repeat: no-repeat;
}
.color input{ background-color:#f1f1f1;}
.files:before {
    position: absolute;
    bottom: 10px;
    left: 0;  pointer-events: none;
    width: 100%;
    right: 0;
    height: 37px;
    content: " or drag it here. ";
    display: block;
    margin: 0 auto;
    color: #2ea591;
    font-weight: 600;
    text-transform: capitalize;
    text-align: center;
}

React file upload component

We will create react file upload component functionality into app.js file.

onChangeHandler=event=>{
    var file = event.target.files[0];
    console.log(file);
    console.log(this.validateSize(event));
    if(this.validateSize(event)){ 
      console.log(file);
  // if return true allow to setState
     this.setState({
      selectedFile: file
      });

    }
  }
  fileUploadHandler = () => {
    const data = new FormData()
    console.log(this.state.selectedFile);
    data.append('file', this.state.selectedFile)
    console.log(data);
    axios.post("https://localhost:8010/api/v1/upload", data)
      .then(res => { // then print response status
        toast.success('upload success')
      })
      .catch(err => { // then print response status
        toast.error('upload fail')
      })

  };
  validateSize=(event)=>{
  let file = event.target.files[0];
  let size = 30000;
  let err = '';
  console.log(file.size);
  if (file.size > size) {
   err = file.type+'is too large, please pick a smaller file\n';
   toast.error(err);
 }
 return true
};

The onChangeHandler method takes file name from the file input field, Also validate file using size, you can add many validation rules to validate the file.

The validateSize method is used to validate file size. If the size is exceeded then throw the message and display using toaster.

The fileUploadHandler method takes file name from state and send a request to node server.

Leave a Reply

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