.Net core 上传文件

 #region 上传文件
        /// <summary>
        /// 上传文件(上传到项目中),返回保存地址(保存文件文件夹+保存文件名称)
        /// </summary>
        /// <returns></returns>
        public JsonResult Upload(IFormFile file)
        {
            var currentDate = DateTime.Now;
            var webRootPath = hostingEnvironment.WebRootPath;//获取项目路径
            try
            {
                var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";
                //创建每日存储文件夹
                if (!Directory.Exists(webRootPath + filePath))
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }
                if (file != null)
                {
                    //文件后缀
                    var fileExtension = Path.GetExtension(file.FileName);//获取文件格式,拓展名

                    var fileSize = file.Length;
                    //判断文件大小
                    if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                    {
                        return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,文件大小超过范围" });
                    }

                    //保存的文件名称(以名称和保存时间命名)
                    var name = file.FileName.Substring(0, file.FileName.LastIndexOf('.'));
                    var saveName = name + "_" + currentDate.ToString("HHmmss") + fileExtension;

                    //文件保存
                    using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    //完整的文件路径
                    var completeFilePath = Path.Combine(filePath, saveName);
                    return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", completeFilePath = completeFilePath });
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    isSuccess = false,
                    resultMsg = "文件保存失败,异常信息为:" + ex.Message
                });
            }
        }
        #endregion

 

上一篇:新!Shiro自定义异常无法被捕获总是抛出AuthenticationException解决方案


下一篇:框架 Spring Boot 技术入门到整合 3-2 Jackson的基本演绎法