Home > Software engineering >  NodeJS undefined is not an object (evaluating 'input.files[0])
NodeJS undefined is not an object (evaluating 'input.files[0])

Time:06-01

I have the following error happening when I try and run my nextjs app.

TypeError: undefined is not an object (evaluating 'input.files[0]')

The reason must be the following

 validateAudioUpload(input){
      var URL = window.URL || window.webkitURL;
      var file = input.files[0];
    
      if (file) {
          var image = new Image();
    
          image.onload = function() {
              if (this.width) {
                   console.log('Image has width, I think it is real image');
                   //TODO: upload to backend
              }
          };
    
          image.src = URL.createObjectURL(file);
      }
    }

in the render return section I have

 <Form.Group controlId="formFile" className="mb-3">
                    <Form.Label>Please select an Image File (500w x 500h)</Form.Label>
                    <Form.Control type="file" onChange={this.validateAudioUpload(this)}/>
                  </Form.Group>

Now because when the page loads it must be trying to run the onChange and it is getting NULL as there is no file selected by the user.

How can I fix this?

CodePudding user response:

Add a simple check before accessing the value:

if (!input?.files || input.files.length === 0) return

var file = input.files[0];

CodePudding user response:

Try this

 validateAudioUpload = (input) => {
      var URL = window.URL || window.webkitURL;
      var file = input.files[0];
    
      if (file) {
          var image = new Image();
    
          image.onload = function() {
              if (this.width) {
                   console.log('Image has width, I think it is real image');
                   //TODO: upload to backend
              }
          };
    
          image.src = URL.createObjectURL(file);
      }
    }
<Form.Control type="file" onChange={this.validateAudioUpload}/>
  • Related