admin管理员组

文章数量:1289582

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.

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';
  }

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.

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';
  }
Share Improve this question asked Nov 15, 2018 at 13:34 Nidhin KumarNidhin Kumar 3,58912 gold badges45 silver badges81 bronze badges 3
  • values.profilePicture.length doesn't work? – Smarticles101 Commented Nov 15, 2018 at 13:44
  • @Smarticles101 It works initially but when i refresh it is not working – Nidhin Kumar Commented Nov 15, 2018 at 13:49
  • You could try checking if values.profilePicture[0] exists? – Smarticles101 Commented Nov 15, 2018 at 13:51
Add a ment  | 

1 Answer 1

Reset to default 9

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.

本文标签: javascriptHow to get the file length for an file in react jsStack Overflow