您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍“怎么使用ASP.NET Core实现文件上传和下载”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么使用ASP.NET Core实现文件上传和下载”文章能帮助大家解决问题。
1.1 获取文件后缀
/// <summary> /// 获取文件后缀 /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> public async static Task<string> GetFileSuffixAsync(string fileName) { return await Task.Run(() => { string suffix = Path.GetExtension(fileName); return suffix; }); }
1.2 上传单文件
public class FileMessage { /// <summary> /// 原文件名称 /// </summary> public string FileName { get; set; } /// <summary> /// 附件名称(协议或其他要进行数据库保存与模型绑定的命名) /// </summary> public string ArgumentName { get; set; } /// <summary> /// 文件大小(KB) /// </summary> public string FileSize { get; set; } /// <summary> /// -1:上传失败 0:等待上传 1:已上传 /// </summary> public int FileStatus { get; set; } /// <summary> /// 上传结果 /// </summary> public string UploadResult { get; set; } /// <summary> /// 创建实例 /// </summary> /// <param name="fileName">原文件名称</param> /// <param name="argumentName">(新)附件名称</param> /// <param name="fileSize">大小</param> /// <param name="fileStatus">文件状态</param> /// <returns></returns> 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 }; } }
/// <summary> /// 上传文件 /// </summary> /// <param name="file">上传的文件</param> /// <param name="fold">要存储的文件夹</param> /// <returns></returns> public async static Task<FileMessage> 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 上传多文件
/// <summary> /// 上传多文件 /// </summary> /// <param name="files">上传的文件集合</param> /// <param name="fold">要存储的文件夹</param> /// <returns></returns> public async static Task<List<FileMessage>> UploadFilesAsync(IFormFileCollection files, string fold) { string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } List<FileMessage> messages = new List<FileMessage>(); 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<ManageProtocolFileController> _logger; public ManageProtocolFileController(IWebHostEnvironment env, ILogger<ManageProtocolFileController> logger) { _env = env; _logger = logger; } /// <summary> /// 协议上传附件 /// </summary> /// <param name="file"></param> /// <returns></returns> [HttpPost("upload")] public async Task<FileMessage> UploadProtocolFile([FromForm] IFormFile file) { return await UploadFileAsync(file, "ManageProtocol"); } }
2.1 获取ContentType属性
/// <summary> /// 获取文件ContentType /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> public async static Task<string> 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<ManageProtocolFileController> _logger; public ManageProtocolFileController(IWebHostEnvironment env, ILogger<ManageProtocolFileController> logger) { _env = env; _logger = logger; } /// <summary> /// 下载附件 /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> [HttpGet("download")] public async Task<FileStreamResult> 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()); } } }
关于“怎么使用ASP.NET Core实现文件上传和下载”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。