How to make file upload progress indication in ReactJS
- User
How to make file upload progress indication in ReactJS
- Assistant
There are several ways to create a file upload progress indication in ReactJS. One common approach is to use the
onProgressevent provided by thefetchorXMLHttpRequestAPI to track the progress of the upload. Here is an example of how you can use thefetchAPI to upload a file and display the progress:codeimport React, { useState } from 'react'; function FileUploader() { const [progress, setProgress] = useState(0); const handleFileChange = async (event) => { const file = event.target.files[0]; const formData = new FormData(); formData.append('file', file); const response = await fetch('/upload', { method: 'POST', body: formData, onUploadProgress: (event) => { setProgress(Math.round((event.loaded / event.total) * 100)); }, }); const data = await response.json(); console.log(data); } return ( <div> <input type="file" onChange={handleFileChange} /> <p>{progress}%</p> </div> ); } export default FileUploader;In this example, the
handleFileChangefunction is triggered when the user selects a file, it creates aFormDataobject, appends the selected file to it and send it to the server using thefetchAPI. TheonUploadProgressevent is used to track the progress of the upload and update theprogressstate accordingly. This state is then used to display the progress percentage on the screen.Another way is to use a library like react-dropzone-uploader, which is a React-based library that provides a complete file upload solution including progress indication.
You can also use other libraries such as react-file-uploader, react-file-upload, etc.