I’m trying to create a form where you can upload multiple images using two file
inputs, see the images as base64 and later submit them using jQuery’s POST
. The problem is that when I select 3 different images, I see only the last one 3 times. I guess the problem is in the for
in the addEventListener
– maybe it’s not in the right place?
<div class="form-group">
<label for="product_photo_1">Photos 1</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="product_photo_1" multiple />
<label class="custom-file-label" for="product_photo_1" data-browse="Select">Please, select a file...</label>
</div>
<div id="product_photo_1_result"></div>
</div>
<div class="form-group">
<label for="product_photo_2">Photos 2</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="product_photo_2" multiple />
<label class="custom-file-label" for="product_photo_2" data-browse="Select">Please, select a file...</label>
</div>
<div id="product_photo_2_result"></div>
</div>
<script>
const convertBase64 = (file) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = () => {
resolve(fileReader.result);
};
fileReader.onerror = (error) => {
reject(error);
};
});
};
const uploadImage = async (event, id) => {
const file = event.target.files[0];
const base64 = await convertBase64(file);
document.getElementById("product_photo_" + id + "_result").innerHTML += '<img src="' + base64 + '" class="img-thumbnail m-2" id="product_photo_' + id + '[]" style="height: 50px;" />';
};
document.getElementById("product_photo_1").addEventListener("change", (event) => {
for(var index = 1; index <= document.getElementById("product_photo_1").files.length; index++) {
uploadImage(event, 1);
}
});
document.getElementById("product_photo_2").addEventListener("change", (event) => {
for(var index = 1; index <= document.getElementById("product_photo_2").files.length; index++) {
uploadImage(event, 2);
}
});
</script>
2
Answers
In
uploadImage
function you are passingevent
argument and select first file every timeInstead you can pass files one by one to the
uploadImage
.Here is the example:
In the event handlers, you are doing a loop, but you are not using the value of index per iteration:
Instead, you will need to pass the index as well, like this: