zoukankan      html  css  js  c++  java
  • 8.mvc core上传文件

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

     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); ; } } }

    以上方法仅供参考

    这是我新写的基于DotnetCore 1.1 写的一个简单的Demo : http://git.oschina.net/quan01994/UploadDemo

  • 相关阅读:
    【转】Loadrunder场景设计篇——添加windows Resource计数器和指标说明
    【转】基于Selenium的web自动化框架(python)
    测试用例
    向SQL Server中导入Excel的数据
    SQl server更新某阶段的匹配关系。
    Python -- print(dataframe)时,省略部分列。
    Python -- Pandas介绍及简单实用【转】
    sqlserver清除缓存,记录查询时间
    ArcMap 10.2 crashes during Loading Document launch stage
    PYTHON:HTTP头设置工具(以附件名为例)
  • 原文地址:https://www.cnblogs.com/quan01994/p/6003244.html
Copyright © 2011-2022 走看看