I'm trying to send images from my form to my php webservice. For now, I'm just trying to see if i receive it well.
and with this code:
html:
<input type="file" multiple name="images" id="images" />
<button id="valider">envoi</button>
Js:
const sample_image = document.getElementById('images');
const valider = document.getElementById('valider');
valider.addEventListener('click', () => {
upload_image(sample_image.files[0]);
})
const upload_image = (file) => {
const form_data = new FormData();
form_data.append('sample_image', file);
console.log(form_data);
fetch(host "add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
});
}
Php:
echo json_encode($_FILES['sample_image']);
It's working but only for 1 image, but i need send many.
and when i try to change my JS to :
upload_image(sample_image.files);
(without the [0]) it's not working.
I just wanted to send an array of files and then use it in my php, but it says
Notice: Undefined index: sample_image
Does it exists a way to do it ?
Thank you.
CodePudding user response:
it's working with :
const upload_image = (files) => {
const form_data = new FormData();
let compt = files.length;
for(let i=0;i<compt;i )
{
form_data.append('sample_images[]', files[i]);
}
console.log(files.length);
console.log(form_data);
fetch(host "add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
}); }
thank you everyone !
CodePudding user response:
You need to change the FormData to receive an array instead of a single item:
const upload_image = (files) => {
const form_data = new FormData();
form_data.append('sample_images[]', files);
console.log(form_data);
fetch(host "add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
}); }