Multiple image upload with Fetch API

Asked

Viewed 125 times

0

I have the following code:

HTML:

<input type="file" name="image[]" class="selecao_arquivo" id="selecao_arquivo" multiple>

Javascript:

sendInsucesso.addEventListener('click', e => {
e.preventDefault()
const files = document.querySelector('.selecao_arquivo')
var formData = new FormData(formInsucesso)
for (let i = 0; i < files.length; i++) {
    formData.append(files[i].name, files[i])
}
fetch('library/fetch/fetch_form_insucesso.php', {
    method: 'POST',
    body: new URLSearchParams(formData)
})
.then(response => response.text())
.then(response => console.log(response))
.catch(error => console.error(error))

})

With send to the PHP however, I receive data from files like [Object File].

inserir a descrição da imagem aqui

  • formData.append(files[i].name, files[i].files[0]), try this

  • @Rogeriosantos paid for the tip, but I still have the same problem brother, I’m looking for other solutions, but it’s hard!

1 answer

0

In fact,

const files = document.querySelector('.selecao_arquivo')

this constant nay is an array, although it is of the Iterable type, this constant is actually an FileList. So, files[i] does not return what you really want.

tries to trade

for (let i = 0; i < files.length; i++) {
    formData.append(files[i].name, files[i])
}

for

for (let i = 0; i < files.length; i++) {
    const file = files.item(i);
    const filename = file.name;
    formData.append(filename, file)
}
  • Thank you very much for the answer, but I still have the same problem! 'image' => array (size=3) 0 => string '[Object File]' (length=13)...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.