Pass array of images in FormData ()

1

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

I know the problem is in the JS code, because when I send the form directly to the php page, it works fine.

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" />
    
asked by anonymous 01.03.2018 / 23:35

1 answer

2

If you want to send all (possible) fields of the form, just use:

let dados = new FormData(this);

If you just want to send some data, you can do the following:

let formData = new FormData();

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