首页 > 代码库 > Ajax异步上传文件

Ajax异步上传文件

需要引用js jquery.form

前端代码

<form action="/Save" id="mainForm" method="post" enctype="multipart/form-data">
 <div class="portlet-body form-horizontal form-bordered form-row-stripped">
        <div class="row-fluid">
            <div class="control-group">
               导入文件:<input type="file" name="FilePath" class="file" id="fileField"> 
            </div>
           
        </div>
    </div>
    <div class="form-actions navbar-fixed-bottom">
        <button id="submit" type="submit" class="btn blue"><i class="icon-ok"></i>提交</button>
    </div>
</form>    
<script src="/Content/Scripts/jquery.form.js"></script>
<script>
    $(function() {
        $("#mainForm").attr("enctype", "multipart/form-data");

        $("#fileField").on("change", function() {
            $("#mainForm").attr("action", "/ImportFile");
            $(form).ajaxSubmit({
                success: function(data) {
                    if (data) {
                       //todo
                    } else {
                        alert("解析文件异常,请检查上传文件");
                    }
                    $("#mainForm").attr("action", "/Save");
                },
            });
        });
    });
</script>

 

后端代码

[HttpPost]
public JsonResult ImportFile(FormCollection collection)
{
    object model = null;
    try
    {
        HttpPostedFileBase fostFile = Request.Files["FilePath"];
        Stream streamfile = fostFile.InputStream;

        var reader = new StreamReader(streamfile);
        string text = reader.ReadToEnd();
        model = XmlHelper.XmlDeserialize<Model>(text, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        throw  new Exception();
    }
    return Json(model, JsonRequestBehavior.AllowGet);
}

 

这样上传文件的问题就解决了。

Ajax异步上传文件