React Js File Upload size Limit Validation

In web development, file upload functionality is a common task with challenges. Key considerations include the image upload size limit, input type file max files, and file validation. This article guides you on using JavaScript and React JS to check file size before upload, validate size and type, and restrict upload types in React JS. Learn to set the input file max size in React and handle errors gracefully, empowering you to create a robust and user-friendly file upload component for your web applications.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I implement file upload size limit validation in React.js?
To implement file upload size limit validation in React.js, you can create your own custom component that uses the HTML input element with the type attribute set to "file". You can then access the file size property of the selected file and compare it with the minimum and maximum file size limits that you define in your component.
React File upload size limit Validation
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [fileSizeError, setFileSizeError] = React.useState(null);
const [fileContent, setFileContent] = React.useState(null);
const [imageSizeKB, setImageSizeKB] = React.useState(0); // Add this state variable
const maxFileSize = 50000; // 50KB
const minFileSize = 1024; // 1KB (you can adjust this as needed)
const handleFileUpload = (event) => {
const file = event.target.files[0];
if (!file) return; // No file selected
if (file.size > maxFileSize || file.size < minFileSize) {
setFileSizeError(
file.size > maxFileSize
? `File size exceeded the limit of ${maxFileSize / 1000} KB`
: `File size is smaller than the minimum limit of ${minFileSize / 1000} KB`
);
setFileContent(null);
setImageSizeKB(0); // Reset image size
return; // Do not process the file if it exceeds the size limit or is too small
}
const reader = new FileReader();
reader.onloadend = () => {
setFileSizeError(null);
setFileContent(reader.result); // Store the file content
setImageSizeKB(file.size / 1024); // Calculate and store image size in KB
};
reader.readAsDataURL(file); // Read file as a data URL (image)
};
return (
<div className="container">
<h3 className="title">React Js File Upload Size Limit Validation</h3>
<input type="file" onChange={handleFileUpload} className="file-input" />
{fileSizeError && <p className="error">{fileSizeError}</p>}
{fileContent && (
<div>
<p className="uploaded-text">Uploaded Image:</p>
<img src={fileContent} alt="Uploaded" className="uploaded-image" />
<p className="image-size">Image Size: {imageSizeKB.toFixed(2)} KB</p>
</div>
)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
React file upload size limit
How to Validate CSV File Before Upload and Set Input File Max Size in React JS
Validate CSV File Before Upload React
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const MAX_FILE_SIZE_MB = 5;
const [errorMessage, setErrorMessage] = useState('');
const isValidFileType = (file) => {
return file.name.endsWith('.csv');
};
const isValidFileSize = (file) => {
return file.size <= MAX_FILE_SIZE_MB * 1024 * 1024;
};
const handleFileChange = (event) => {
const selectedFile = event.target.files[0];
if (selectedFile) {
if (isValidFileType(selectedFile) && isValidFileSize(selectedFile)) {
setErrorMessage(''); // Clear any previous error message
} else {
setErrorMessage('Invalid file. Please check file type and size.');
}
}
};
return (
<div className="container">
<h1>CSV File Uploader</h1>
<input type="file" onChange={handleFileChange} />
<p style={{ color: 'red' }}>{errorMessage}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Image Upload Size Limit and File Type Restriction in React JS
Image validation in react js
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const handleFileChange = (event) => {
const file = event.target.files[0];
// File type validation
if (!file.type.startsWith('image/')) {
alert('Please upload only image files.');
return;
}
// File size validation (in bytes)
const maxSize = 5 * 1024 ;
if (file.size > maxSize) {
alert('File size exceeds the limit (5 KB).');
return;
}
};
return (
<div className="container">
<h3 className="title">React Js File Upload Size Limit Validation</h3>
<input type="file" onChange={handleFileChange} />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>