weixin_33725807 2015-06-16 22:19 采纳率: 0%
浏览 27

如何为Ajax上传文件

I'm trying to submit a form via ajax which has some images The following code returns an object (in console.form), "FormData", however how do I use it and or retrieve it, and whether it is right.

$("#form_galeria").unbind('submit').bind('submit', function(e) {
    e.preventDefault();
    var url = 'salvarGaleria.do';

    var form;
    form = new FormData();

    form.append('fileUpload', e.target.files);
    console.log(form);

    $.ajax({
        type: "POST",
        url: url,
        data: $("#form_galeria").serialize(),
        processData: false,
        contentType: false,
        success: function(result) {
            console.log(result);
        },
        error: function(err) {
            console.log(err.status + ' - ' + err.statusText);
        }
    });

    $('#multiplas').modal('hide');
    return false;
});
  • 写回答

1条回答 默认 最新

  • weixin_33727510 2015-06-16 22:23
    关注

    Set the ajax data option to your FormData object. You will need to add whatever field values to the FormData object as well if you wish to send those along with the file upload. Also you have to append each indvidual file you cannot just append the e.target.files collection

    for(var i=0; i<e.target.files.length; i++){
        form.append("fileUpload[]",e.target.files[i]);
    }
    //or if you are only doing a single file
    //form.append("fileUpload",e.target.files[0]);
    
    form.append("someField",jQuery("#someField").val());
    form.append("someOtherField",jQuery("#someOtherField").val());
    
    $.ajax({
        type: "POST",
        url: url,
        data: form,
        processData: false,
        contentType: false,
        success: function(result){
          console.log(result);
        },
        error: function(err){
          console.log(err.status + ' - ' + err.statusText);
        }
    });
    
    评论

报告相同问题?