8.mvc core上传文件

版权声明:此文章转载自_infocool

原文链接:http://www.infocool.net/kb/DotNet/201610/205607.html

如需转载请联系听云College团队成员小尹 邮箱:yinhy#tingyun.com

以下方法均是个人,仅供参考

 public interface IFileHelper
    {
        /// <summary>
        /// 保存文件 (返回 Test.jpg) 出错就返回 error|错误信息
        /// </summary>
        string SaveFile(IFormFile file, FileCategory fc);
        bool DeleteFile(string fileName, FileCategory fc);
    }
public class FileHelper: IFileHelper
    {
        private readonly IHostingEnvironment _hostingEnv;
        private static readonly Random _rdm = new Random();
        public FileHelper(IHostingEnvironment env)
        {
            _hostingEnv = env;
        }
        /// <summary>
        /// 保存文件(返回新文件名)
        /// </summary>
        /// <param name="file"></param>
        /// <param name="fc"></param>
        /// <returns></returns>
        public string SaveFile(IFormFile file, FileCategory fc)
        {
            var path = GetUploadPath(fc);
            var targetDirectory = Path.Combine(_hostingEnv.WebRootPath, string.Format(path));
            //这里进行随机文件名
            var fileName = GetRandName(file);
            var savePath = Path.Combine(targetDirectory, fileName);
            try
            {
                file.CopyTo(new FileStream(savePath, FileMode.Create));
                //return   Upload/NewsPhoto/Test.jpg
                //返回文件名
                return fileName;
            }
            catch
            {
                return "false";
            }
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fullPath"></param>
        /// <returns></returns>
        public bool DeleteFile(string fileName, FileCategory fc)
        {
            var path = GetUploadPath(fc);
            var targetDirectory = Path.Combine(_hostingEnv.WebRootPath, string.Format(path));
            //物理完整路径
            var physicalPath = Path.Combine(targetDirectory, fileName);
            try
            {
                File.Delete(physicalPath);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 相对路径 /Upload/NewsPhoto/Test.jpg
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetFullPath(FileCategory fc,string fileName)
        {
            var path = GetUploadPath(fc);
            return Path.Combine(string.Format(path), fileName);
        }
        /// <summary>
        /// 获取到上传路径(Upload//CasePhoto//)
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        public static  string GetUploadPath(FileCategory fc)
        {
            switch (fc)
            {
                case FileCategory.CasePhoto:return "Upload//CasePhoto//";
                case FileCategory.NewsPhoto:return "Upload//NewsPhoto//";
                case FileCategory.CompanyPhoto: return "Upload//CompanyPhoto//";
                case FileCategory.PositionPhoto: return "Upload//PositionPhoto//";
                case FileCategory.Partner: return "Upload//Partner//";
                default:return "";
            }
        }
        public static string GetRandName(string oldFileName)
        {
            //获取后缀
            var extension= GetExtensionWithDot(oldFileName);
            //产生新的文件名
            var newFileName = DateTime.Now.ToFileTime().ToString() + _rdm.Next(999);
            //组合
            return newFileName + extension;
        }
        public static string GetRandName(IFormFile file)
        {
            var fileName = file.FileName;
            var randName = GetRandName(fileName);
            return randName;
        }
        public enum FileCategory
        {
            /// <summary>
            /// 案例文章插图
            /// </summary>
            CasePhoto,
            /// <summary>
            /// 新闻文章插图
            /// </summary>
            NewsPhoto,
            /// <summary>
            /// 公司介绍插图
            /// </summary>
            CompanyPhoto,
            /// <summary>
            /// 职位描述插图
            /// </summary>
            PositionPhoto,
            /// <summary>
            /// 合作伙伴
            /// </summary>
            Partner,
           
        }
        /// <summary>
        /// 获取到后缀名的方法
        /// </summary>
        public static string GetExtensionWithDot(string fileName)
        {
            var dotIndex = fileName.LastIndexOf('.');
            if (dotIndex < 0 || dotIndex >= fileName.Length) return string.Empty;
            return fileName.Substring(dotIndex);
        }
}
 
//添加一个FileHelper的依赖注入(依赖注入的实现类一定要写构造方法)
//该方法是单例模式
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IFileHelper, FileHelper>();
}

在startup中加入

新建一个UploadController 专门处理上传

public class UploadController : Controller
    {
        private readonly IFileHelper _fileHelper;
        public UploadController(IFileHelper fileHelper)
        {
            _fileHelper = fileHelper;
        }
        /// <summary>
        /// 专门为Case的文件上传 有可能有两个name 不支持H5 wangEditorFormFile  支持h5 wangEditorH5File
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string UploadCompanyPhoto(IFormFile wangEditorFormFile = null, IFormFile wangEditorH5File = null)
        {
            //全部用/,windows支持/
            return Upload(FileCategory.CompanyPhoto, wangEditorFormFile, wangEditorH5File);
        }
        private string Upload(FileCategory fc ,IFormFile wangEditorFormFile = null, IFormFile wangEditorH5File = null)
        {
            if (wangEditorFormFile == null && wangEditorH5File == null)
            {
                return "error|无文件上传";
            }
            var file = wangEditorFormFile == null ? wangEditorH5File : wangEditorFormFile;
            var result = _fileHelper.SaveFile(file, fc);
            //判断是否错误
            if (result == "false")
            {
                return "error|上传失败";
            }
            else
            {
                return "http://" + Request.Host.ToString() + "/" + FileHelper.GetFullPath(fc, result); ;
            }
        }
    }

以上方法仅供参考


想阅读更多技术文章,请访问听云技术博客,访问听云官方网站感受更多应用性能优化魔力。

关于作者

coco秋洁

我爱学习,学习使我快乐

我要评论

评论请先登录,或注册