When working with file uploads in React, it's a good idea to add validation checks to make sure the uploaded file follows specific rules. Here's an example of a file upload form that checks the file type and size:
import React, { useState } from 'react';
const FileUploadForm = () => {
const [selectedFile, setSelectedFile] = useState(null);
const [fileErrors, setFileErrors] = useState('');
const validateFile = (file) => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
const maxSize = 5 * 1024 * 1024; // 5MB
if (!allowedTypes.includes(file.type)) {
return 'Invalid file type. Please upload a JPEG, PNG, or GIF file.';
}
if (file.size > maxSize) {
return 'File size exceeds the maximum limit of 5MB.';
}
return null; // No errors
};
const handleFileChange = (event) => {
const file = event.target.files[0];
if (file) {
const error = validateFile(file);
if (error) {
setFileErrors(error);
} else {
setFileErrors('');
setSelectedFile(file);
}
}
};
const handleSubmit = (event) => {
event.preventDefault();
if (selectedFile) {
// Perform file upload action (e.g., send file to server)
console.log('File uploaded:', selectedFile);
// Reset selected file and errors
setSelectedFile(null);
setFileErrors('');
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Choose File:
<input type="file" onChange={handleFileChange} />
</label>
{fileErrors && <p style={{ color: 'red' }}>{fileErrors}</p>}
<button type="submit" disabled={!selectedFile}>
Upload
</button>
</form>
</div>
);
};
export default FileUploadForm;
In this example,
In this example,
The
validateFile
function looks at the chosen file's type and size, comparing them to set rules. Change theallowedTypes
andmaxSize
variables based on what you need.The
handleFileChange
function starts when a file is picked. It usesvalidateFile
and updates the component state.The
handleSubmit
function takes care of the form submission. It uploads the file if it's valid.The form button won't work until a valid file is chosen.
This example shows simple file type and size checks. You might need more advanced checks or use outside libraries for file checking in a real-world work setting. Also, think about adding server-side checks for better security.