I am developing a simple drag and drop image upload option.
When I drag the image on the drag area it's showing me the uploaded image. That's good. Now, I drag multiple images at a time.
Using this JavaScript code I am Uploading Image:
function uploadFile(files) {
let url = 'process.php'
let formData = new FormData();
let allowedExt = ['jpg', 'jpeg', 'png', 'gif'];
for (const [key, value] of Object.entries(files)) {
let extension = value.name.split(".").pop();
if (allowedExt.includes(extension) == false) {
alert('Invalid file formate, we are only accepting ' + allowedExt.join(", ") + ' file formates');
return false;
}
formData.append('files[]', value);
previewFile(value, value.name);
}
fetch(url, {
method: 'POST',
body: formData,
})
.then((data) => {
console.log('Success');
})
.catch((error) => {
console.log(error);
})
}
For previewing the Image
function previewFile(file, fileName) {
let reader = new FileReader();
reader.readAsDataURL(file);
console.log( reader );
reader.onload = function () {
let html = '';
html += '<div class="col-md-4"><div class="item" id="item"><img src="' + reader.result + '" alt="" class="img-fluid filter-me"><span>' + fileName + '</span></div></div>';
loadImage.innerHTML += html;
// let filterMe = document.querySelector('.filter-me').src;
// console.log(filterMe);
// for( let i =0; i < filterMe.length; i++) {
// console.log( filterMe[i]);
// // filterMe[i].addEventListener( 'click', function () {
// // console.log( this );
// // localStorage.setItem("imgData", this.src);
// // });
// }
}
reader.onloadend = function () {
let filterMe = document.querySelector(".filter-me");
filterMe.addEventListener("click", function () {
console.log( this );
});
}
}
Now, on this function you can see I want to see this this value using console.log( this );
But it's showing me first upload image this value not other images when I click on other images :(
- Is there anything I am wrong and how can I do this?
- Is there any better code to achive this?