ajaxfileupload-上传文件示例

1.引用文件 ajaxfileupload.js

 

@{
    ViewBag.Title = "数据导入";
    Layout = "~/Views/Shared/_IndexLayout.cshtml";
}
<!--单个文件-->
<script src="~/Content/scripts/uploadify/ajaxfileupload.js"></script>

<script>
    var loadingstatus = "";
  
    var tmpkey = request('tmpkey'); //这里特别约定为了简约处理模板的key对应的解析方法名称和模板key一致
    var keyvalue = request('keyvalue'); 
    $(function () {
        var url = '../../Master/ImportTemplate/DownloadTmp?tmpKey=' + tmpkey;
        $('#lr-import').attr('href', url);
        $('#uploadFile').bind("change", function (e) {
            //btn_importdata();
        });

  //  beginCount();
    });

    var timeID;

    function btn_importdata() {
        $('#msg').html("");
        var path = $("#uploadFile").val();
        if (!path) {
            dialogMsg("请选择要上传的文件!", 0);
            return;
        }
        loadingstatus = "loading";
        $('#msg').append("<br>执行中,这可能需要一些时间,请耐心等待....</br>");
        $('#msg').append("<br>如果检测到有错误的请您按照提示排查处理后重新导入....</br>");
        $.ajaxFileUpload({
            url: "../../CVRM/ImportExcel/ImportData?key=" + keyvalue + "&funName=" + tmpkey,
            secureuri: false,
            fileElementId: 'uploadFile',
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    var result = data.msg;
                    $('#msg').append(result);
                }
                else {
                     
                    dialogMsg(data.message, 0);
                }
            }
            
        });
    }

    function btn_close() {
        dialogClose();
    }

    function beginCount() {
    timeID = setInterval("getMsg()", 2000);
    }
    function stopCount() {
        clearInterval(timeID);
    }
    function getMsg() {
        if (loadingstatus == "loading") {
            $.ajax({
                url: "../../CVRM/ImportExcel/GetImportMsg",
                dataType: "json",
                async: true,
                type: 'GET',
                success: function (data) {
                    console.log(data);
                    if (data.errorcode==0) {
                        $('#msg').append(data.message);
                        if (data.message=="stop") {
                            stopCount();
                        }
                    } else {
                        stopCount();
                    }
                    
                }
            })
        }
    
    }

    
</script>
<form id="form1" style="margin-left: 1px; margin-right: 1px;">
    <div class="formHead">
        <div class="mcp_container">
            <div class="col-xs-8 mcp-form-item" style="padding-left:5px;">
                <input id="uploadFile" name="uploadFile" type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
            </div>
            <div class="col-xs-4 mcp-form-item">
                <div class="btn-group">
                    <a id="lr-choose" class="btn btn-default" onclick="btn_importdata()"><i class="fa fa-sign-in"></i>&nbsp;开始导入</a>
                    <a id="lr-import" class="btn btn-default" >  <i class="fa fa-download"></i>&nbsp;下载模板</a>
                </div>
            </div>
            <div  id="msg">
              
            </div>

        </div>
 
    </div>
 

</form>
 

 

 

3.后台接收

   public ActionResult ImportData(string key,string funName="")
        {
            try
            {
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

                if (files != null && files.Count > 0 && files[0].ContentLength > 0 && !string.IsNullOrEmpty(files[0].FileName))
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + @"Upload\temp\";
                    DirectoryInfo dir = new DirectoryInfo(path);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                    string filename = Path.GetFileName(files[0].FileName);
                    if (!string.IsNullOrEmpty(filename))
                    {

                        var keyValue = Guid.NewGuid().ToString();
                        string FileEextension = Path.GetExtension(files[0].FileName);
                        filename = keyValue + FileEextension;
                        string Fullfilename = Path.Combine(path, filename);
                        files[0].SaveAs(Fullfilename); //保存服务器

                        //写入数据库
                        ImportExcelBiz importBiz = new ImportExcelBiz();
                        ImportExcelResultEntity result = importBiz.ImportData(key, funName, Fullfilename);
                         
                        //用完即删
                        if (System.IO.File.Exists(Fullfilename))
                        {
                            //如果存在则删除
                            System.IO.File.Delete(Fullfilename);
                        }
 
                        return new ReponseModel { status = true, msg = result.Msg };
                    }
                    else
                    {
                        return Error("没有发现您上传的文件名,可能是浏览器兼容问题,请您换个浏览器试试! 详情: files[0].FileName  filename为null");
                    }

                }
                else
                {
                    return HttpNotFound("没有发现您要上传的文件!");
                }

            }
            catch (Exception ex)
            {
                return Error("导入excel到报价中出现了异常 详情:"+ex.Message);
            }
          
          
           
     
        }

    }

  

posted @ 2018-03-30 11:16  笨笨鱼~  阅读(1036)  评论(0编辑  收藏  举报