ASP.NET Core實現(xiàn)文件上傳和下載
更新時間:2022年07月26日 11:47:26 作者:965201314.cn
這篇文章主要為大家詳細介紹了ASP.NET Core實現(xiàn)文件上傳和下載,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了ASP.NET Core實現(xiàn)文件上傳和下載的具體代碼,供大家參考,具體內容如下
一、文件上傳
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é)議或其他要進行數(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> ? ? ? ? /// 上傳結果 ? ? ? ? /// </summary> ? ? ? ? public string UploadResult { get; set; } ? ? ? ? /// <summary> ? ? ? ? /// 創(chuàng)建實例 ? ? ? ? /// </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">要存儲的文件夾</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> ? ? ? ? /// 協(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 + "下載后臺客戶協(xié)議附件:" + request.FileName); ? ? ? ? ? ? ? ? return File(stream, contentType, fileName); ? ? ? ? ? ? } ? ? ? ? ? ? catch (Exception e) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? _logger.LogError(e, "用戶:" + createName + "下載后臺客戶協(xié)議附件出錯,出錯原因:" + e.Message); ? ? ? ? ? ? ? ? throw new Exception(e.ToString()); ? ? ? ? ? ? } ? ? ? ? } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
asp.net 自定義控件實現(xiàn)無刷新上傳圖片,立即顯示縮略圖,保存圖片縮略圖
自定義控件實現(xiàn)無刷新上傳圖片,立即顯示縮略圖,保存圖片縮略圖2010-01-01數(shù)據(jù)庫SqlParameter 的插入操作,防止sql注入的實現(xiàn)代碼
今天學習了一下SqlParameter的用法,原來這么寫是為了防止sql注入,破壞數(shù)據(jù)庫的。并自己動手連接了數(shù)據(jù)庫。2013-04-04ASP.NET實現(xiàn)數(shù)據(jù)的添加(第10節(jié))
這篇文章主要介紹了ASP.NET如何實現(xiàn)數(shù)據(jù)的添加,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2015-08-08