阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

简单介绍ASP.NET Core实现文件上传和下载

75次阅读
没有评论

共计 4128 个字符,预计需要花费 11 分钟才能阅读完成。

导读 这篇文章主要为大家详细介绍了 ASP.NET Core 实现文件上传和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了 ASP.NET Core 实现文件上传和下载的具体代码,供大家参考,具体内容如下

一、文件上传

1.1 获取文件后缀

/// 
/// 获取文件后缀
/// 
/// 文件名称
/// 
        public async static Task GetFileSuffixAsync(string fileName)
        {return await Task.Run(() =>
            {string suffix = Path.GetExtension(fileName);
                return suffix;
            });
        }

1.2 上传单文件

public class FileMessage
    {
        /// 
        /// 原文件名称
        /// 
        public string FileName {get; set;}
 
        /// 
        /// 附件名称 (协议或其他要进行数据库保存与模型绑定的命名)
        /// 
        public string ArgumentName {get; set;}
 
        /// 
        /// 文件大小 (KB)
        /// 
        public string FileSize {get; set;}
 
        /// 
        /// -1:上传失败 0:等待上传 1:已上传
        /// 
        public int FileStatus {get; set;}
 
        /// 
        /// 上传结果
        /// 
        public string UploadResult {get; set;}
 
        /// 
        /// 创建实例
        /// 
        /// 原文件名称
        /// (新) 附件名称
        /// 大小
        /// 文件状态
        /// 
        public static FileMessage CreateNew(string fileName,
            string argumentName,
            string fileSize,
            int fileStatus,
            string uploadResult)
        {return new FileMessage()
            {
                FileName = fileName,
                ArgumentName = argumentName,
                FileSize = fileSize,
                FileStatus = fileStatus,
                UploadResult = uploadResult
            };
        }
    }
/// 
/// 上传文件
 /// 
 /// 上传的文件
 /// 要存储的文件夹
 /// 
        public async static Task UploadFileAsync(IFormFile file, string fold)
        {
            string fileName = file.FileName;
            string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/";
            if (!Directory.Exists(path))
            {Directory.CreateDirectory(path);
            }
            string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await GetFileSuffixAsync(file.FileName);
            string fileSize = Math.Round((decimal)file.Length / 1024, 2) + "k";
            string filePath = Path.Combine(path, argumentName);
            try
            {using (FileStream stream = new FileStream(filePath, FileMode.Create))
                {await file.CopyToAsync(stream);
                }
                return FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功");
            }
            catch (Exception e)
            {return FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败:" + e.Message);
            }
        }

1.3 上传多文件

/// 
/// 上传多文件
/// 
/// 上传的文件集合
/// 要存储的文件夹
/// 
        public async static Task> UploadFilesAsync(IFormFileCollection files, string fold)
        {string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/";
            if (!Directory.Exists(path))
            {Directory.CreateDirectory(path);
            }
            List messages = new List();
            foreach (var file in files)
            {
                string fileName = file.FileName;
                string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await GetFileSuffixAsync(file.FileName);
                string fileSize = Math.Round((decimal)file.Length / 1024, 2) + "k";
                string filePath = Path.Combine(path, argumentName);
                try
                {using (FileStream stream = new FileStream(filePath, FileMode.Create))
                    {await file.CopyToAsync(stream);
                    }
                    messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功"));
                }
                catch (Exception e)
                {messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败,失败原因:" + e.Message));
                }
            }
            return messages;
        }
[Route("api/[controller]")]
    [ApiController]
    public class ManageProtocolFileController : ControllerBase
    {
        private readonly string createName = "";
        private readonly IWebHostEnvironment _env;
        private readonly ILogger _logger;
        public ManageProtocolFileController(IWebHostEnvironment env,
            ILogger logger)
        {
            _env = env;
            _logger = logger;
        }
         
        /// 
        /// 协议上传附件
        /// 
        /// 
        /// 
        [HttpPost("upload")]
        public async Task UploadProtocolFile([FromForm] IFormFile file)
        {return await UploadFileAsync(file, "ManageProtocol");
        }
    }
二、文件下载

2.1 获取 ContentType 属性

/// 
/// 获取文件 ContentType
/// 
/// 文件名称
 /// 
        public async static Task GetFileContentTypeAsync(string fileName)
        {return await Task.Run(() =>
            {string suffix = Path.GetExtension(fileName);
                var provider = new FileExtensionContentTypeProvider();
                var contentType = provider.Mappings[suffix];
                return contentType;
            });
        }

2.2 执行下载

[Route("api/[controller]")]
[ApiController]
    public class ManageProtocolFileController : ControllerBase
    {
        private readonly string createName = "";
        private readonly IWebHostEnvironment _env;
        private readonly ILogger _logger;
        public ManageProtocolFileController(IWebHostEnvironment env,
            ILogger logger)
        {
            _env = env;
            _logger = logger;
        }
         
        /// 
        /// 下载附件
        /// 
        /// 文件名称
        /// 
        [HttpGet("download")]
        public async Task Download([FromQuery] string fileName)
        {
            try
            {
                string rootPath = _env.ContentRootPath + @"/Upload/ManageProtocolFile";
                string filePath = Path.Combine(rootPath, fileName);
                var stream = System.IO.File.OpenRead(filePath);
                string contentType = await GetFileContentTypeAsync(fileName);
                _logger.LogInformation("用户:" + createName + "下载后台客户协议附件:" + request.FileName);
                return File(stream, contentType, fileName);
            }
            catch (Exception e)
            {_logger.LogError(e, "用户:" + createName + "下载后台客户协议附件出错,出错原因:" + e.Message);
                throw new Exception(e.ToString());
            }
        }
}

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥玩云-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计4128字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中