MVC下Ajax上传文件

需求:采用ajax方式上传文件到服务器

1.前端代码

   

 <a href="javascript:void(0);" onclick="importMulitExcel()">模板导入</a>
 <input type="file" id="file" onchange="getFilePath()" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;" />

2.Jquery代码

 function importMulitExcel() {
            //触发 文件选择的click事件
            $("#file").trigger("click");
        }
/* 获取文件的路径*/
        function getFilePath() {
            //alert($("#file").val());
            filePath = $("#file").val();
            if (filePath == "") {
                alert("请选择要上传的文件!");
                return false;
            } else {
                UpLoadExcelFile(filePath);
            }
        }

        /* 上传文件并返回服务器端存储路径*/
        function UpLoadExcelFile(filePath) {
            var formData = new FormData();
            formData.append('file', $('#file')[0].files[0]);
            $.ajax({
                url: "UpLoadExcel?path=" + filePath + "",
                type: "POST",
                data: formData,
                cache: false,
                contentType: false, //必须false才会避开jQuery对 formdata 的默认处理 XMLHttpRequest会对 formdata 进行正确的处理
                processData: false, //必须false才会自动加上正确的Content-Type
                dataType: "json",
                success: function (res) {
                    if (res.success) {
                       alert('导入成功');
                    } else {
                        alert('导入失败');
                    }
                }
            });
        }

3.后台代码

 

 /// <summary>
        /// 将本地上传的文件保存到服务器
        /// </summary>
        /// <param name="FileData"></param>
        /// <returns></returns>
        public JsonResult UpLoadExcel(HttpPostedFileBase FileData)
        {
            try
            {
                FileData = Request.Files[0];
                // 没有文件上传,直接返回
                if (FileData == null || string.IsNullOrEmpty(FileData.FileName) || FileData.ContentLength == 0)
                {
                    return Json(new { Success = true, Message = "未获取到文件!" });
                }
                string ID = Guid.NewGuid().ToString();
                string FileName = Request["path"].ToString();//;FileData.FileName;
                string SaveName = string.Format("{0}{1}", ID.ToString(), Path.GetExtension(FileName));
                //文件存储的相对路径
                string virtualPath = string.Format("Upload/{0}/{1}/{2}/{3}",
                    DateTime.Now.Year.ToString(),
                    DateTime.Now.ToString("MM"),
                    DateTime.Now.ToString("dd"),
                    SaveName);
                string fullFileName = this.Server.MapPath("~/" + virtualPath);
                string path = Path.GetDirectoryName(fullFileName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!System.IO.File.Exists(fullFileName))
                {
                    FileData.SaveAs(fullFileName);
                }

                return Json(new { Success = true, Filepath = virtualPath, Message = "导入成功!" });
            }
            catch (Exception ex)
            {
                return Json(new { Success = false, Message = ex.Message });
            }
        }

 

posted @ 2017-08-15 15:47  努力的小样  阅读(1079)  评论(0编辑  收藏  举报
Copyright ©2017 爱睡觉的程序猿