ASP.NET Core单文件和多文件上传及删除文件

废话不多说,直接上代码,单独封装1个文件类,公共调用就行

  public class FileController : Controller
    {
        #region 构造函数
        private readonly IWebHostEnvironment hostingEnv;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="env"></param>
        public FileController(IWebHostEnvironment env)
        {
            this.hostingEnv = env;
        }
        #endregion

        #region 单个文件上传
        /// <summary>
        /// 单个文件上传(上传到项目中),返回保存地址(保存文件文件夹+保存文件名称)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadFile()
        {
            var file = Request.Form.Files[0];
            var currentDate = DateTime.Now;
            var webRootPath = hostingEnv.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, returnMsg = "上传失败,文件大小超过范围" });
                    }

                    //保存的文件名称(以名称和保存时间命名)
                    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 = "上传成功", path = completeFilePath });
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, returnMsg = "上传失败,未检测上传的文件信息~" });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    isSuccess = false,
                    returnMsg = "文件保存失败,异常信息为:" + ex.Message
                });
            }
        }
        #endregion

        #region 多文件上传

        /// <summary>
        ///  多文件上传
        /// </summary>
        /// <param name="formCollection">表单集合值</param>
        /// <returns>服务器存储的文件信息</returns>

        public JsonResult MultiFileUpload(IFormCollection formCollection)
        {
            var currentDate = DateTime.Now;
            var webRootPath = hostingEnv.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") 
            var uploadFileRequestList = new List<UploadFileRequest>();
            try
            {
                //FormCollection转化为FormFileCollection
                var files = (FormFileCollection)formCollection.Files;

                if (files.Any())
                {
                    foreach (var file in files)
                    {
                        var uploadFileRequest = new UploadFileRequest();

                        var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

                        //创建每日存储文件夹
                        if (!Directory.Exists(webRootPath + filePath))
                        {
                            Directory.CreateDirectory(webRootPath + filePath);
                        }

                        //文件后缀
                        var fileExtension = Path.GetExtension(file.FileName);//获取文件格式,拓展名

                        //判断文件大小
                        var fileSize = file.Length;

                        if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                        {
                            continue;
                        }

                        //保存的文件名称(以名称和保存时间命名)
                        var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + 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);

                        uploadFileRequestList.Add(new UploadFileRequest()
                        {
                            FileName = saveName,
                            FilePath = completeFilePath
                        });
                    }
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, returnMsg = "上传失败,未检测上传的文件信息~" });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, returnMsg = "文件保存失败,异常信息为:" + ex.Message });
            }

            if (uploadFileRequestList.Any())
            {
                return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", filePathArray = uploadFileRequestList });
            }
            else
            {
                return new JsonResult(new { isSuccess = false, returnMsg = "网络打瞌睡了,文件保存失败" });
            }
        }

        /// <summary>
        /// 对文件上传响应模型
        /// </summary>
        public class UploadFileRequest
        {
            /// <summary>
            /// 文件名称
            /// </summary>
            public string FileName { get; set; }

            /// <summary>
            /// 文件路径
            /// </summary>
            public string FilePath { get; set; }
        }

        #endregion

        #region 删除本地文件方法
        /// <summary>
        /// 删除本地文件方法
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public JsonResult UpLoadDelete(string path)
        {
            try
            {
                if (string.IsNullOrEmpty(path))
                {
                    return new JsonResult(new { isSuccess = false, returnMsg = "删除失败,文件路径不能为空~" });
                }
                string dir = hostingEnv.WebRootPath + path;
                if (System.IO.File.Exists(dir))
                {
                    System.IO.File.Delete(dir);
                    return new JsonResult(new { isSuccess = true, returnMsg = "删除成功" });
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, returnMsg = "删除失败,未检测到删除的文件信息~" });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, returnMsg = "文件保存失败,异常信息为:" + ex.Message });
            }
        }
        #endregion

        #region BootStrap 删除文件模拟调用

        /// <summary>
        /// BootStrap 删除文件模拟调用
        /// </summary>
        /// <returns>因为Bootstrap fileinput必要请求1个方法才能回调</returns>
        public JsonResult BsDelFileUpload()
        {
            return new JsonResult(new { isSuccess = true, returnMsg = "" });
        }
        #endregion
    }

 

posted on 2022-06-17 09:26  小乐丶  阅读(473)  评论(0编辑  收藏  举报