Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file length for an file in react js

I am using file upload in that i have added a validation if there is no file then display an error message. I am able to get the file length but when the page gets refreshed i am getting the image as well. I don't know how to get the file length from it.can anyone help me to sort this issue Thanks in advance.

enter image description here

Conditions i have used:

    if (!values.profilePicture) {
    errors.profilePicture = 'Employee Image Required';
  } else if (values.profilePicture && values.profilePicture.length === 0) {
    console.log('values.profilePicture.length', Object.keys(values.profilePicture).length);
    errors.profilePicture = 'Employee Image Required';
  }
like image 702
Nidhin Kumar Avatar asked Sep 15 '25 09:09

Nidhin Kumar


1 Answers

Every file which you want to upload has file size property you can get that property onChange event.

<input type="file" accept="image/*" id="profilePic" onChange={(e)=>this.uploadImage(e)}>

and uploadImage function should be like

uploadImage=(e)=>{
  let file = e.target.files[0];
    if (file && !file.name) {
       window.alert("Please select a file");
       return false;
    }
    if (file.size > 10e6) {
      window.alert("Please upload a file smaller than 10 MB");
      return false;
    }
}

Note: 10e6 is 10mb file size.

like image 52
Nilesh Kant Avatar answered Sep 16 '25 22:09

Nilesh Kant