Ajax.BeginForm 异步上传附件 替代方案

  

一:问题描述

    含有文件信息表单内容,想通过异步上传到服务器,但是使用Ajax.BeginForm上传时,后台无法获取文件信息 

二:解决方案

    通过  $.ajaxFileUpload 可以实现文件及文本内容上传到服务器的需求, 但是需要引入ajaxfileupload.js文件

三:注意事项

   (1):

            //表单文本内容,
            var data = { RealName: RealName1, Telephone: Telephone1, FlightNumber: FlightNumber1, FlightDate: FlightDate1, ComplaintContent: ComplaintContent1 };
            $.ajaxFileUpload({
                method: "POST",
                url: "/controller/action",//需要链接到服务器地址
                secureuri: true,
                fileElementId: 'id_ComplaintsPicture',//文件选择框的id属性(也就是type="file"的input的id属性,并不需要把文件值写入到data中)
                data: data,//$("#form_2").serialize(),//此写法,只上传文件还可以,文件加文本内容上传无效
                success: function (data) {
                    //上传成功之后的操作
                    var obj = $.parseJSON(data);//返回值形式需要在 ajaxFileUpload.js文件中修改一下,因为它对你原生的后台返回值进行了修饰,这里我的后台返回值形式为{"result": "0","msg": "返回内容"}
                    if (obj.result == "0") {
                        if (obj.msg) {
                            alert(obj.msg);
                        } else {
                            alert("失败!");
                        }
                        $("#sub_btn").attr("disabled", false);//id为提交按钮(type="button")
                    } else {
                        alert("成功!");
                        window.location.reload();
                    }
                }, error: function (ret) {
                    //上传失败之后的操作
                    alert("网络错误!请重试!");
                }
            });

 (2) ajaxFileUpload.js 文件修改 位置

     uploadHttpData 函数的最后返回值修改成 return r.responseText;

 (3 ajaxFileUpload.js 文件的 handleError 可能因为你引用的jquery版本的问题而报错“函数不存在"

     解决方法:
                 在ajaxFileUpload.js 文件中加入以下代码

    

    handleError: function (s, xhr, status, e) {
        // If a local callback was specified, fire it
        if (s.error) {
            s.error.call(s.context || s, xhr, status, e);
        }

        // Fire the global callback
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
        }
    }

 四 后台接收方式 .net

   

 public string complaint(HttpPostedFileBase[] ComplaintsPicture)

 这里就不介绍如何接收上传的文本框内容了,注意ComplaintsPicture就是type="file"的input ,它的name名称,上面代码表示可以接收多个文件

posted on 2016-08-24 23:31  CodeArtist  阅读(387)  评论(0编辑  收藏  举报