jQuery AJAX文件上传

I'm trying to pass an array of files in the ajax request here is my code :

$(document).on('click', '#submit_edit_discussion', function (event) {
    event.preventDefault();
    var channel_id = $('#channel_id').val();
    var discussion_id = $('#discussion_id').val();
    var title = $('#title').val();
    var content = $('#content').val();
    var image_choice = [''];
    var image = [''];
    var new_image = [''];
    for (var i = 0; i < $('.images').data('images-count'); i++) {
        image_choice[i] = $('input[name="image_choice_' + i + '"]:checked').val();
        image[i] = $('#image_' + i).data('image-id');
    }
    for (var i = 0; i < $('#images_i').val(); i++) {
        var j = i + 1;
        new_image[i] = $('#new_image_' + j + '').prop('files')[0];
    }
    $.post('edit', {
        'content': content,
        '_token': $('input[name=_token]').val(),
        'channel_id': channel_id,
        'title': title,
        'discussion_id': discussion_id,
        'image': image,
        'image_choice': image_choice,
        'new_image': new_image
    }, function (data) {
        console.log(data);
    });
});

The array new_image contains the images when i log it, it shows correctly but when i add it to the object data of the post request it wont work

To upload files you need to send a FormData object that contains the binary data. You cannot serialise the files to strings - which is what your current code is attempting to do.

Note that you can massively simplify the process by using the constructor of FormData which accepts a form Element. You can achieve this by hooking to the submit event of the form instead of the click of the submit button. If all the values are not contained within input elements within the form then you can use the append() method to add them manually.

The data will then be populated in the FormData object with the keys of the input elements. Note that data in this method cannot be provided in arrays; each single value must have it's own key. You can serialise/deserialise data if you prefer to store it in a single key, but this will need to be done manually on the client and server respectively.

Here's a basic working example:

$(document).on('submit', '#yourForm', function(e) {
  e.preventDefault();

  $.ajax({
    url: 'edit',
    type: 'post',
    data: new FormData(this),
    processData: false,
    contentType: false
  }, function(data) {
    console.log(data);
  });
});