简体   繁体   English

如何为Ajax上传文件

[英]How do file upload for 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. 我试图通过具有一些图像的ajax提交表单以下代码返回一个对象(在console.form )“ FormData ”,但是我如何使用和/或检索它以及它是否正确。

$("#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;
});

Set the ajax data option to your FormData object. 将ajax data选项设置为FormData对象。 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. 如果您希望将这些字段值与文件上传一起发送,则还需要向FormData对象添加任何字段值。 Also you have to append each indvidual file you cannot just append the e.target.files collection 另外,您必须附加每个单独的文件,而不能仅附加e.target.files集合

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);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM