Pass image array in Formdata()

Asked

Viewed 564 times

1

I need to add a array of images on FormData, but only the first image is passing.

I know the problem is in the code JS why when I send the form directly to the page php, works normal.

Javascript

var url = $(this).attr('action');
var dados = new FormData();

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

$.ajax({
    url: url,
    type: 'POST',
    data: dados,
    dataType: 'json',
    processData: false,
    contentType: false,
    success: function(data) {
        console.log(data);
    }
});

HTML

<label for="1">Imagem 1</label>
<input type="file" name="imagem[]" id="1"/>

<label for="1">Imagem 2</label>
<input type="file" name="imagem[]" id="2" />

<label for="1">Imagem 3</label>
<input type="file" name="imagem[]" id="3" />

1 answer

2


If you want to submit all (possible) form fields, just use:

let dados = new FormData(this);

If you just want to send some data, you can do it as follows:

let formData = new FormData();

$(this).find('input:file').each(function(index, element) {
    formData.append( 'imagem[]', element.files[0] )
});

Browser other questions tagged

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