React Image Upload with Preview, Percentage Progress Bar Tutorial

Last updated on: by Editorial Team

React image upload, preview, progress bar tutorial; If a new file uploading task has been assigned to you in react, this guide will manifest a pragmatic solution.

In this tutorial, you will find out the profound way on how to use drag and drop to upload single and multiple image files in react and show image preview after file upload. Moreover, you will learn how to create a percentage progress bar to track the uploading progress of the files using the third party react-dropzone-uploader, html5-file-selector and Bootstrap packages.

Drag and drop offer an easy solution to upload images and files. The common notion about drop zone is that it ramps up the user experience; a user can select and drag and drop images and files.

Here are the topics that we are going to address in this guide.

  • Create react app from scratch
  • Configure react dropzone package
  • Create drag and drop component
  • Add maximum files validation
  • Add custom style to dropzone module
  • Use dropzone properties and methods

How to Upload Image Files, Show Image Preview with Progress Percentage Bar in React

  • Step 1: Install New React Project
  • Step 2: Install Bootstrap Package
  • Step 3: Add React Dropzone Package
  • Step 4: Install HTML File Selector Package
  • Step 5: Create and Register File Upload Component
  • Step 6: Implement React Dropzone in React Component
  • Step 7: Start React Application

Install New React Project

Invoke the first step by creating a brand new React app; if you already know this process, then you are good to go to the subsequent step.

npx create-react-app react-social

Get into the project root.

cd react-social

Install Bootstrap Package

This step is optional; we are using the Bootstrap CSS framework to ramp up the UI of the image upload module; you can ignore this plugin if you want.

npm i bootstrap

Add React Dropzone Package

In this section, you will likely install the react-dropzone-uploader package in React application; make sure to add the required packages’ in the file upload component file.

npm i react-dropzone-uploader

Install HTML File Selector Package

Next, install the html5 file selector package; it eloquently deals with custom input control that handles the files array chosen by file input control.

npm i html5-file-selector

Create and Register File Upload Component

Ideally, components are independent and reusable pieces of code that are used to manage code eloquently. They are very much identical to programming functions; however, they work independently and return HTML through a render() function.

Next, create src/components folder, then fileUpload.component.js file within.

Once the new component is created, then place the following code in the src/components/fileUpload.component.js file.

import React from 'react';
import 'react-dropzone-uploader/dist/styles.css'
import Dropzone from 'react-dropzone-uploader'
import { getDroppedOrSelectedFiles } from 'html5-file-selector';


const FileUploadComponent = () => {
    
};

export default FileUploadComponent;

There after, move to the src/App.js file and update the given code within the file.

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

import FileUploadComponent from './components/fileUpload.component';

function App() {
  return (
    <div className="App container mt-5">
      <FileUploadComponent />
    </div>
  );
}

export default App;

Implement React Dropzone in React Component

Next, we are going to integrate the drag and drop image files upload with the image preview feature, not just that; we will also show you how to create a percentage progress bar and how to blitzkrieg several other functionalities that are essential and build using dropzone’s methods and event handlers.

Add code in src/components/fileUpload.component.js file.

import React from 'react';
import 'react-dropzone-uploader/dist/styles.css'
import Dropzone from 'react-dropzone-uploader'
import { getDroppedOrSelectedFiles } from 'html5-file-selector'


const FileUploadComponent = () => {

    const fileParams = ({ meta }) => {
        return { url: 'https://httpbin.org/post' }
    }

    const onFileChange = ({ meta, file }, status) => { 
        console.log(status, meta, file) 
    }

    const onSubmit = (files, allFiles) => {
        allFiles.forEach(f => f.remove())
    }

    const getFilesFromEvent = e => {
        return new Promise(resolve => {
            getDroppedOrSelectedFiles(e).then(chosenFiles => {
                resolve(chosenFiles.map(f => f.fileObject))
            })
        })
    }

    const selectFileInput = ({ accept, onFiles, files, getFilesFromEvent }) => {
        const textMsg = files.length > 0 ? 'Upload Again' : 'Select Files'

        return (
            <label className="btn btn-danger mt-4">
                {textMsg}
                <input
                    style={{ display: 'none' }}
                    type="file"
                    accept={accept}
                    multiple
                    onChange={e => {
                        getFilesFromEvent(e).then(chosenFiles => {
                            onFiles(chosenFiles)
                        })
                    }}
                />
            </label>
        )
    }

    return (
        <Dropzone
            onSubmit={onSubmit}
            onChangeStatus={onFileChange}
            InputComponent={selectFileInput}
            getUploadParams={fileParams}
            getFilesFromEvent={getFilesFromEvent}
            accept="image/*,audio/*,video/*"
            maxFiles={5}
            inputContent="Drop A File"
            styles={{
                dropzone: { width: 600, height: 400 },
                dropzoneActive: { borderColor: 'green' },
            }}            
        />
    );
};

export default FileUploadComponent;

Start React Application

In the eventual step, you have to start the react app; this helps to check the subtle nuances in the file upload functionality we have just added in react.

npm start

Here is the url, run it on the browser to view the app.

http://localhost:3000

React Dropzone Uploader Example

Conclusion

React drag and drop library makes the file uploading exorbitantly easy. It offers tons of features that can eloquently let you build single and multiple file uploads with subtle nuances. Nothing can refrain you from customizing the dropzone component in react, thanks to react dropzone uploader plugin.