jQuery的Ajax表单提交包含文件 [英] Jquery ajax form submit that contains files

查看:246
本文介绍了jQuery的Ajax表单提交包含文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的表格,包含文件附件:

这是我的形式看起来的样子:

在这里输入的形象描述

表格将被提交到这个动作:

  [HttpPost]
公众的ActionResult AddReceivingConfirm(DTOreceiving项,IEnumerable的< HttpPostedFileBase>文件上传)
    {        返回PartialView();
    }

通过Ajax调用是:

 的$(document)。在('点击','输入[类型=提交。genericSubmit',函数(){阿贾克斯//通用功能的任何形式的提交ŧ        如果(!$(形式#ValidateForm)。有效()){
                返回false;
        };
        。VAR frmData = $('。genericForm')序列化();
        VAR frmUrl = $('。genericForm')ATTR('行动')。
            $阿贾克斯({
              类型:'后',
              网址:frmUrl,
              数据:frmData,              成功:功能(E){
                 $('#目标')HTML(E);
             }
         });
         返回false;
 });

一切除了的IEnumerable&LT完美结合; HttpPostedFileBase> 总是结果

我的窗体的文件部分是这样做的:

 < TR>
 &所述; TD>附件#1:其中; / TD>
 &所述; TD列跨度=3>
     <输入ID =文件1类型=文件名称=文件上传/>
 < / TD> < / TR>  &所述; TR>
  &所述; TD>附件#2:其中; / TD>
 &所述; TD列跨度=3>
     <输入ID =文件2类型=文件名称=文件上传/>
 < / TD> < / TR>  &所述; TR>
  &所述; TD>附件#3:其中; / TD>
 &所述; TD列跨度=3>
     <输入ID =文件3类型=文件名称=文件上传/>
 < / TD> < / TR>

我已经试过了括号版等,但它不会绑定。

研发的一个小时后,我读过,这是不可能的(?))做文件通过使用Ajax,除非传统的iframe张贴。我不知道我的动作会是什么,我还挺想避免使用插件,所以我想知道是否有从我的形式直接访问这些文件?一些哈克的方式

这是我的表单:

 使用(Html.BeginForm(AddReceivingConfirm,仓库管理系统,FormMethod.Post,新{ID =ValidateForm,@class =genericForm,ENCTYPE =多部分/表单数据}))


解决方案

不幸的是,jQuery的连载()方法将不包括输入文件的元素。所以,你的文件不会被包含在序列化值。

你应该做的是创建一个 FORMDATA 对象,该文件追加到。您需要添加表单字段值,以及此相同的FORMDATA对象。你可以简单的通过所有的输入字段环和添加。此外,在Ajax调用,您需要指定过程数据的contentType 属性值

 的$(document)。在('点击','输入[类型=提交。genericSubmit',函数(E){    亦即preventDefault(); // prevent默认提交行为。    VAR FDATA =新FORMDATA();    $(输入[名称=文件上传]')。每个(函数(A,B){
        VAR的FileInput = $('输入[名称=文件上传]')[A];
        如果(fileInput.files.length大于0){
            var文件= fileInput.files [0];
            fdata.append(文件上传文件);
        }
    });    //你可以更新jQuery选择,如果你想使用一个CSS类
    $(输入[类型=文本)。每个(函数(X,Y){
        fdata.append($(y)的.attr(名称),$(y)的.VAL());
    });    VAR frmUrl = $('。genericForm')ATTR('行动')。
    $阿贾克斯({
        类型:'后',
        网址:frmUrl,
        数据:FDATA,
        过程数据:假的,
        的contentType:假的,
        成功:功能(E){
            $('#目标')HTML(E);
        }
    });});

I have a very long form that contains files attachment:

this is how my form looks like:

The form will be submitted to this action:

[HttpPost]
public ActionResult AddReceivingConfirm(DTOreceiving entry,IEnumerable<HttpPostedFileBase> fileUpload)
    {

        return PartialView();
    }

through ajax call which is:

$(document).on('click', 'input[type="submit"].genericSubmit', function () {                    //generic function for ajax submit of ANY FORMS t

        if (!$("form#ValidateForm").valid()) {
                return false;
        };


        var frmData = $('.genericForm').serialize();
        var frmUrl = $('.genericForm').attr('action');
            $.ajax({
              type: 'post',
              url: frmUrl,
              data: frmData,

              success: function (e) {
                 $('#target').html(e);
             }
         });
         return false;
 });

everything is binding perfectly except the IEnumerable<HttpPostedFileBase>which always results to null,

the file part of my form is done like this:

 <tr>
 <td>Attachment #1: </td>
 <td colspan="3">
     <input id="file1" type="file" name="fileUpload" />
 </td>

 </tr>

  <tr>
  <td>Attachment #2: </td>
 <td colspan="3">
     <input id="file2" type="file" name="fileUpload" />
 </td>

 </tr>

  <tr>
  <td>Attachment #3: </td>
 <td colspan="3">
     <input id="file3 "type="file" name="fileUpload" />
 </td>

 </tr>

I have tried the brackets version and etc but it won't bind.

After an hour of researching, i've read that it's not possible(?) )to do file posting conventionally through the use of Ajax unless iframe. I am not sure of what my action will be, i kinda want to avoid using plugin so i wanna know if there is some "hacky" ways to access the files directly from my form?

this is my form:

using (Html.BeginForm("AddReceivingConfirm", "Wms", FormMethod.Post, new { id = "ValidateForm", @class = "genericForm" , enctype="multipart/form-data"}))

解决方案

Unfortunately the jQuery serialize() method will not include input file elements. So your files are not going to be included in the serialized value.

What you should be doing is creating a FormData object, append the files to that. You need to append the form field values as well to this same FormData object. You may simply loop through all the input field and add it. Also, in the ajax call, you need to specify processData and contentType property values to false.

$(document).on('click', 'input[type="submit"].genericSubmit', function(e) {

    e.preventDefault(); // prevent the default submit behavior.

    var fdata = new FormData();

    $('input[name="fileUpload"]').each(function(a, b) {
        var fileInput = $('input[name="fileUpload"]')[a];
        if (fileInput.files.length > 0) {
            var file = fileInput.files[0];
            fdata.append("fileUpload", file);
        }
    });

    // You can update the jquery selector to use a css class if you want
    $("input[type='text'").each(function(x, y) {
        fdata.append($(y).attr("name"), $(y).val());
    });

    var frmUrl = $('.genericForm').attr('action');
    $.ajax({
        type: 'post',
        url: frmUrl,
        data: fdata,
        processData: false,
        contentType: false,
        success: function(e) {
            $('#target').html(e);
        }
    });

});

这篇关于jQuery的Ajax表单提交包含文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆