MVC 接收文件

  [HttpPost]
        public ActionResult Layedit()
        {
            var files = Request.Files; //获得所上传的所有文件 
            if (files.Count > 0)
            {
                HttpPostedFileBase file = files[0];  //获得首个文件

                //判断文件大小
                if (file.ContentLength > 1024 * 1024 * 10)  //1MB 1024//字节 1MB=1024KB  1KB = 1024字节
                {
                    return Json(new { code = 1, msg = "上传失败!" });
                }
                //判断文件扩展名
                if (file.ContentType.IndexOf("image") == -1) //不是图片
                {
                    return Json(new { code = 1, msg = "上传失败!" });
                }


                string filePathName = (DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_" + file.FileName).Trim().Replace(";", ""); //新建文件名//2018-06-02-16-20-55_QQ截图20180601101500.png 日期+文件名
                string filePathimg = "UploadImg/" + DateTime.Now.ToString("yyyy-MM-dd"); //文件要存的目录
                string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, filePathimg);//文件路径 //\BFWebManage\UploadImg               
                if (!System.IO.Directory.Exists(localPath))  //判断路径是否存在
                {
                    System.IO.Directory.CreateDirectory(localPath);//创建文件目录
                }

                file.SaveAs(Path.Combine(localPath, filePathName));//保存文件    //将两个字符串组合成一个路径

                return Json(new { code = 0, msg = "", data = new { src = "../../" + filePathimg + "/" + filePathName, title = "图片名称" } }); //返回图片信息
            }
            return Json(new { code = 1, msg = "上传失败!" });

        }

 

posted @ 2018-03-07 15:16  enych  阅读(285)  评论(0编辑  收藏  举报