Input file as append in Formdata

Asked

Viewed 293 times

0

How can I insert images like append in a Formdata?

I’m trying this way, but when I use the console.log to verify the variable dados, the imagens is empty.

var dados = new FormData();

$('.copiar-elemento').each(function() {
   $(this).find('input:file').each(function(index, element) {
         dados.append('cores[imagens][]', element.files[0]);
    });
});
  • Would not be $(this).find("select[name*='tamanho']").each(function(index, element) { dados.append('cores[tamanhos][]', element.value); }); ??

  • That’s right, thanks! I tried to use the same structure to do the same with a file field. Would you have to modify something else to work? I put the code in the question.

  • Simply inform the third parameter dados.append('cores[imagens][]', element.files[0], 'imagem.jpg'); see the documentation

  • Even with third parameter does not insert inside the formdata. When I use the.log console in the "data" shows the empty "images".

1 answer

0

Try it with this:

var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('cores[imagens][]', file);
});

$.ajax({
    type: 'POST',
    url: '/sua/url',
    cache: false,
    contentType: false,
    processData: false,
    data : data,
    success: function(result){
        console.log(result);
    },
    error: function(err){
        console.log(err);
    }
})

Browser other questions tagged

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