Handling file uploads with progress tracking in a React.js app involves using the HTML <input type="file">
element to allow users to select files, using the Fetch API or Axios to upload the selected files to the server, and tracking the upload progress using the progress
event provided by the XHR (XMLHttpRequest) object or Axios. Here's a basic example using the Fetch API:
Create a File Upload Component:
Create a component named FileUpload.js
:
jsximport React, { useState } from 'react';
const FileUpload = () => {
const [selectedFile, setSelectedFile] = useState(null);
const [uploadProgress, setUploadProgress] = useState(0);
const handleFileChange = (event) => {
setSelectedFile(event.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append('file', selectedFile);
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData,
onUploadProgress: (progressEvent) => {
const progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
setUploadProgress(progress);
},
});
if (response.ok) {
console.log('File uploaded successfully');
} else {
console.error('Failed to upload file');
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
{uploadProgress > 0 && <progress value={uploadProgress} max="100">{uploadProgress}%</progress>}
</div>
);
};
export default FileUpload;
Style Your Component:
Style your component as needed to match your application's design.
Handle File Upload on the Server:
On the server-side, handle the file upload request and process the uploaded file accordingly.
Testing:
Test your file upload component by selecting a file and clicking the upload button. You should see the progress of the upload displayed in a progress bar.
With this setup, you have a basic file upload component in your React.js app that allows users to select files, track the progress of the upload, and upload files to the server. You can further enhance this functionality by adding error handling, multiple file uploads, and additional features as needed.