One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image.
This is the existing code:
var imageLoader = document.getElementById('fUpload2');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas2');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
document.getElementById("imageCanvas2").style.height = canvas.height;
document.getElementById("imageCanvas2").style.maxWidth = "200px";
document.getElementById("imageCanvas2").style.maxHeight = "200px";
document.getElementById("imageCanvas2").style.border = "1px solid #000";
}
img.src = event.target.result;
var alte= canvas.height;
}
reader.readAsDataURL(e.target.files[0]);
}
.image-upload-gal > input {
display: none;
}
<div class="well">
<form class="form-horizontal" role="form" method="post" action="/ServiceUpload.php" enctype="multipart/form-data">
<div class="form-group" style="padding:14px;">
<div class="image-upload-gal" >
<label for="fUpload2">
Add foto
</label>
<input type="file" name="fUpload" id="fUpload2" />
<br>
<canvas id="imageCanvas2" ></canvas>
</div>
</div>
<button class="btn btn-primary pull-right" type="submit" value="f_upload" name="up" style="margin-top: -20px;">Submit Photo</button>
</form>
</div>
In addition to this code, here is another piece of code (it's a long story :D)
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
.thumb {
height: 180px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
input{
display:none;
}
<div class="image-upload" >
<label for="upload">
Add foto
</label>
<input type="file" id="upload" name="fUpload" />
<input type="hidden" name="up" value="f_upload" />
<output id="list"></output>
</div>
<button class="btn btn-primary pull-right" type="submit" value="newpost" name="NewPost" style="margin-top: -10px;">Submit</button>
</form>