0

i have to make an image preview component with the File API and validations. Here is the JS

JS

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

 reader.onloadend = function () {
   if (preview.width.toFixed(0) > 400 || preview.height.toFixed(0) > 400) { 
     alert('enter a 400x400px or less image');
   } else {
      preview.src = reader.result;
   }
 }
 if (file) {
   reader.readAsDataURL(file);
 } else {
   preview.src = "";
 }  
}

HTML

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image">

The images are shown, but now i have to make some validations, so when a user try to upload the same image twice, the file it's only read it once (i think it's because the onChange event detect that the file is the same so there's no change) .

What can i do to be able to read the image all the times that the user upload it?

JSFIDDLE https://jsfiddle.net/j5gyv7pm/10/

Franco Manzur
  • 373
  • 1
  • 7
  • 19
  • 1
    You can set your input's `value` to `null`, this will clear the `files` list. Also note that you should rather use the `URL.createObjectURL()` method to preview an image from an input element – Kaiido Mar 07 '17 at 12:26
  • Possible duplicate of [How can I clear an HTML file input with JavaScript?](http://stackoverflow.com/questions/1703228/how-can-i-clear-an-html-file-input-with-javascript) – Kaiido Mar 07 '17 at 12:27
  • @Kaiido this works! document.querySelector('input[type=file]').value = ''; – Franco Manzur Mar 07 '17 at 13:17

0 Answers0