0

Following is the code I copied from the internet to show the preview of the image before uploading to the server. If I click upload image it triggers click event on input element and uploads the image. likewise if I cick on Delete I want to remove it from input element or from the web storage itself, I want to remove only that particular image so that it will not be processed by the server.

<input type="file" id="files" />
<img id="image" />
<div id="uploadimage"> upload image</div>
<a href="#"> Delete</a>

<script>
document.getElementById("uploadimage").onclick=function(){
    document.getElementById("files").click();
};
document.getElementById("files").onchange = function () {
    var reader = new FileReader();

    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("image").src = e.target.result;

    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};
</script>

Thanks in advance

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77
  • 1
    `this.files` is read-only.. You can not update it..You can remove element from the `DOM` and also save this state somewhere in the hidden `input` element and avoid manipulating it over server.. – Rayon Mar 18 '16 at 09:54
  • 1
    @RayonDabre, except for clearing it : `this.value=''`=> `this.files = []` But no way to clear a single file in multi-files input though. The only way would be to store your files in an array, then post only the wanted ones to the server with a `FormData` Object. But there is a dupe of it, let me find it out... – Kaiido Mar 18 '16 at 09:55
  • @Kaiido thanks bro I will try it and post back – Sugumar Venkatesan Mar 18 '16 at 09:55
  • Here is the dupe, kinda dirty when I look back at it, and since the answer isn't accepted I can't mark it as dupe but you may find your happiness : http://stackoverflow.com/questions/30823275/html5-file-api-with-multiple-files-in-sequence-instead-of-all-at-once/30825504#30825504 – Kaiido Mar 18 '16 at 10:01

1 Answers1

0

You can add id attribute to the link and complete the javascript with the following code:

document.getElementById("delete").onclick = function () {
  document.getElementById("image").src = null;
  document.getElementById("files").value = '';
  return false;
};

jsfiddle

Andrey Etumyan
  • 1,394
  • 11
  • 17