Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reupload the type=file once uploaded till submit

i am making a form where i need to uplaod images where i can change the uploaded image until i submit the form

function previewImage() {
  var thisElement = event.target
  var file = thisElement.files;
  var fileReader = new FileReader();
  fileReader.onload = function(event) {
    thisElement.nextElementSibling.setAttribute("src", event.target.result);
  }
  thisElement.style.display = 'none';
  fileReader.readAsDataURL(file[0])
};
<input type="file" id="file1" accept="image/*" onchange="previewImage();">
<img id="display1"><br>
<input type="file" id="file2" accept="image/*" onchange="previewImage();">
<img id="display2"><br>
<input type="file" id="file3" accept="image/*" onchange="previewImage();">
<img id="display3"><br>
<input type="file" id="file4" accept="image/*" onchange="previewImage();">
<img id="display4"><br>

i want to change the uploaded file but i can’t do so once i uploaded the file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would do this by:

  • Wrap each image in a <label> for the relevant input
  • Update your image loaded event to target the image specifically using nextElementSibling.querySelector("img")
  • Wrap the fileReader.readAsDataURL(file[0]) in an if to avoid an error when the user cancels file selection.

That way you can click the image to change it after the first time it is set.

function previewImage() {
  var thisElement = event.target
  var file = thisElement.files;
  var fileReader = new FileReader();
  fileReader.onload = function(event) {
    thisElement.nextElementSibling.querySelector("img").setAttribute("src", event.target.result);
  }
  thisElement.style.display = 'none';
  if (file.length) {
    fileReader.readAsDataURL(file[0])
  }
};
<input type="file" id="file1" accept="image/*" onchange="previewImage();">
<label for="file1"><img id="display1"></label><br>
<input type="file" id="file2" accept="image/*" onchange="previewImage();">
<label for="file2"><img id="display2"></label><br>
<input type="file" id="file3" accept="image/*" onchange="previewImage();">
<label for="file3"><img id="display3"></label><br>
<input type="file" id="file4" accept="image/*" onchange="previewImage();">
<label for="file4"><img id="display4"></label><br>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading