.Net Core文件上传

https://www.cnblogs.com/viter/p/10074766.html

1.内置了很多种绑定模型  缺少了一个FromFileAttribute 绑定模型 需要自己实现一个

    public class FromFileAttribute : Attribute, IBindingSourceMetadata
    {
        public BindingSource BindingSource => BindingSource.FormFile;
    }

2.实现一个文件上传类

    public class UserFile
    {
        public string FileName { get; set; }
        public long Length { get; set; }
        public string Extension { get; set; }
        public string FileType { get; set; }

        private readonly static string[] Filters = { ".jpg", ".png", ".bmp" };
        public bool IsValid => !string.IsNullOrEmpty(this.Extension) && Filters.Contains(this.Extension);

        private IFormFile file;
        public IFormFile File
        {
            get { return file; }
            set
            {
                if (value != null)
                {
                    this.file = value;

                    this.FileType = this.file.ContentType;
                    this.Length = this.file.Length;
                    this.Extension = this.file.FileName.Substring(file.FileName.LastIndexOf('.'));
                    if (string.IsNullOrEmpty(this.FileName))
                        this.FileName = this.FileName;
                }
            }
        }

        public async Task<string> SaveAs(string destinationDir = null)
        {
            if (this.file == null)
                throw new ArgumentNullException("没有需要保存的文件");

            if (destinationDir != null)
                //如果路径不存在  则创建路径(包括子路径)
                Directory.CreateDirectory(destinationDir);
            var newName = DateTime.Now.Ticks;
            //定义文件名
            var newFile = Path.Combine(destinationDir ?? "", $"{newName}{this.Extension}");
            //建立一个文件缓冲流   也就是开辟一块内存空间
            using (FileStream fs = new FileStream(newFile, FileMode.CreateNew))
            {
                //将上传的文件拷贝到目标流中
                await this.file.CopyToAsync(fs);
                //清除文件缓冲区 并将所有缓冲数据写入到文件中
                fs.Flush();
            }
            return newFile;
        }
    }

3.实现上传接口

        [HttpPost]
        public async Task<IActionResult> JcbPost([FromFile]UserFile file)
        {
            if (file == null || !file.IsValid)
                return new JsonResult(new { code = 500, message = "不允许上传的文件类型" });
            //获取当前程序运行的根目录  可以不需要
            var directory = System.IO.Directory.GetCurrentDirectory();
            string newFile = string.Empty;
            if (file != null)
                //在Web.Host根路径下(相对路径)
                newFile = await file.SaveAs("data/files/images");

            return new JsonResult(new { code = 0, message = "成功", url = newFile });
        }
原文地址:https://www.cnblogs.com/jiangchengbiao/p/10482339.html