Ubuntu 18.04 + Firefox 70.0
I want to send files to my server PHP script by an XMLHttpRequest
.
I test with the simplest HTML markup and JS script, according to :
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
and
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
I can't transfer the selected files in the declared FormData object, not with the new FormData(FormObject), nor with populating the FormData with the files in a loop.
<form id='mcp-form0' enctype="multipart/form-data" method="post">
<input type="file" name="fichier" id="fichier" multiple="">
</form>
<script>
let inputElement = document.getElementById('fichier');
inputElement.addEventListener('change', handleFiles, false);
function handleFiles() {
let formDataConstructor = new FormData(document.getElementById('mcp-form0')),
formDataLoop = new FormData(),
control = "\nSelected : \n",
fileList = this.files;
for (let i = 0, n = fileList.length; i < n; i++) {
let file = fileList[i];
formDataLoop.append("userfile[]", file, file.name);
control += "File : " + file.name + " de " + file.size + " bytes (" + file.type + ")\n";
}
console.log(control);
console.log(fileList);
console.log(formDataConstructor);
console.log(formDataLoop);
}
</script>
The console answer is :
Selected :
Fichier : RetourPantalonMinouTiq.pdf de 33699 octets (application/pdf)
Fichier : rel01png.pdf de 47511 octets (application/pdf)
Fichier : rel00png.pdf de 101450 octets (application/pdf)
FileList(3) [ File, File, File ]
FormData { }
FormData { }
The detail of var 'control' shows that the loop made a correct job, but the 'formDataConstructor' FormData constructor-populated object, which would contain the 3 files I selected, is empty, idem the 'formDataLoop' FormData object populated in the loop.
I expected both of them to be :
FormData { File, File, File }
I can't find my mistake. Would you please help me?