How to use FormData for AJAX file upload?

后端 未结 9 1362
不思量自难忘°
不思量自难忘° 2020-11-21 06:13

This is my HTML which I\'m generating dynamically using drag and drop functionality.

9条回答
  •  抹茶落季
    2020-11-21 06:47

    
    

    jQuery with CodeIgniter file upload:

    var formData = new FormData($('#upload_form')[0]);
    
    formData.append('tax_file', $('input[type=file]')[0].files[0]);
    
    $.ajax({
        type: "POST",
        url: base_url + "member/upload/",
        data: formData,
        //use contentType, processData for sure.
        contentType: false,
        processData: false,
        beforeSend: function() {
            $('.modal .ajax_data').prepend('');
            //$(".modal .ajax_data").html("
    Hold on...
    "); $(".modal").modal("show"); }, success: function(msg) { $(".modal .ajax_data").html("
    " + msg +
                "
    "); $('#close').hide(); }, error: function() { $(".modal .ajax_data").html( "
    Sorry! Couldn't process your request.
    " ); // $('#done').hide(); } });

    you can use.

    var form = $('form')[0]; 
    var formData = new FormData(form);     
    formData.append('tax_file', $('input[type=file]')[0].files[0]);
    

    or

    var formData = new FormData($('#upload_form')[0]);
    formData.append('tax_file', $('input[type=file]')[0].files[0]); 
    

    Both will work.

提交回复
热议问题