1

I have a function to upload an image with FileReader method, if the file image was choose it will showing as a preview image before i upload it, i want to make some validation to read the image width, if it false the preview image should not appear, i'm confused how to make it, since i can not place the file reader inside the image.load scoope: here is my code below :

var input = document.getElementById('fileTrigger');
var el = document.createElement('IMG');


input.addEventListener('change', function({target}){
  
  var file = target.files[0];
  var reader = new FileReader();
  var image  = new Image(); 
  
    reader.onload = function(e){
      
      if(file) {
        image.onload = function(e){
          var width = e.target.width;
          console.log(width);
          
          if(width !== 100){
            console.log('fail')
          }
          
        }
        image.src = reader.result;
      }
      
      
      el.src = e.target.result;
      document.body.appendChild(el)
    }
    reader.readAsDataURL(file);
});    
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
</head>
<body>
<input type="file" id="fileTrigger">
</body>
</html> 
Anas
  • 971
  • 13
  • 28
Riantori
  • 317
  • 1
  • 4
  • 14
  • 1
    Refer answers of this stack question might help https://stackoverflow.com/questions/8903854/check-image-width-and-height-before-upload-with-javascript – Neha Tawar Mar 22 '18 at 05:04

1 Answers1

1

var input = document.getElementById('fileTrigger');
var el = document.createElement('IMG');
var elResult


input.addEventListener('change', function({target}){
  el.src=""
  var file = target.files[0];
  var reader = new FileReader();
  var image  = new Image(); 
  
    reader.onload = function(e){
      elResult=e.target.result;
      if(file) {
        image.onload = function(e){
          var width = e.target.width;
          console.log(width);
          
          if(width >=300){
            console.log('fail')
            
          }else{
          el.src = elResult
      document.body.appendChild(el)
      }
          
        }
        image.src = reader.result;
      }
      
      
      
    }
    reader.readAsDataURL(file);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
</head>
<body>
<input type="file" id="fileTrigger">
</body>
</html>

Hope this will helps you..:)

Rahul Mahadik
  • 11,668
  • 6
  • 41
  • 54