網(wǎng)站首頁 編程語言 正文
本文實(shí)例為大家分享了ASP.NET Core實(shí)現(xiàn)文件上傳和下載的具體代碼,供大家參考,具體內(nèi)容如下
一、文件上傳
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>
? ? ? ? /// 附件名稱(協(xié)議或其他要進(jìn)行數(shù)據(jù)庫保存與模型綁定的命名)
? ? ? ? /// </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>
? ? ? ? /// 上傳結(jié)果
? ? ? ? /// </summary>
? ? ? ? public string UploadResult { get; set; }
? ? ? ? /// <summary>
? ? ? ? /// 創(chuàng)建實(shí)例
? ? ? ? /// </summary>
? ? ? ? /// <param name="fileName">原文件名稱</param>
? ? ? ? /// <param name="argumentName">(新)附件名稱</param>
? ? ? ? /// <param name="fileSize">大小</param>
? ? ? ? /// <param name="fileStatus">文件狀態(tài)</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">要存儲(chǔ)的文件夾</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">要存儲(chǔ)的文件夾</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>
? ? ? ? /// 協(xié)議上傳附件
? ? ? ? /// </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 執(zhí)行下載
[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 + "下載后臺(tái)客戶協(xié)議附件:" + request.FileName);
? ? ? ? ? ? ? ? return File(stream, contentType, fileName);
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _logger.LogError(e, "用戶:" + createName + "下載后臺(tái)客戶協(xié)議附件出錯(cuò),出錯(cuò)原因:" + e.Message);
? ? ? ? ? ? ? ? throw new Exception(e.ToString());
? ? ? ? ? ? }
? ? ? ? }
}
原文鏈接:https://blog.csdn.net/qq_42799562/article/details/117958873
相關(guān)推薦
- 2022-12-24 利用C語言實(shí)現(xiàn)頁面置換算法的詳細(xì)過程_C 語言
- 2023-05-18 Python使用requirements.txt和pip打包批量安裝的實(shí)現(xiàn)_python
- 2022-11-20 Postgresql刪除數(shù)據(jù)庫表中重復(fù)數(shù)據(jù)的幾種方法詳解_PostgreSQL
- 2022-10-14 SpringCloud 微服務(wù)與遠(yuǎn)程調(diào)用測試
- 2022-03-08 Asp.NetCore3.1開源項(xiàng)目升級(jí)為.Net6.0的方法實(shí)現(xiàn)_實(shí)用技巧
- 2022-09-17 ASP.NET?Core項(xiàng)目中集成TypeScript_實(shí)用技巧
- 2022-05-28 關(guān)于docker?compose安裝redis集群的問題(集群擴(kuò)容、集群收縮)_docker
- 2022-07-19 AI與Python人工智能啟發(fā)式搜索概念理解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支