Shubham Jha Shubham Jha - 1 month ago 6
HTML Question

Removing uploaded Image

I can upload an image and preview it using the following HTML code and function. But what after I select the image and preview, I don't want to upload the image? I need to refresh the page or reset entire form. How can I just remove the uploaded image?

HTML:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server">
<input type="file" id="imgInp" style="margin-top: 4px;" />
<img id="status-img" src="#" alt="" width="150" height="150" />
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</div>
</form>


Javascript:

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#status-img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}

$("#imgInp").change(function(){
readURL(this);
});


Please help me guys!

Answer

Subham, the JS code you are using is not upload your image to server. It just convert your selected image into BASE64 and show it on an image tag. If you want to remove that image from preview, just reset the src tag of image like:

$('#status-img').attr('src', '');

or

$('#status-img').removeAttr('src');

And to remove the selected image from input type image:

$('#imgInp').val('');