ASP.NET Core實(shí)現(xiàn)文件上傳和下載
本文實(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()); ? ? ? ? ? ? } ? ? ? ? } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- asp.net core實(shí)現(xiàn)文件上傳功能
- ASP.NET Core文件上傳與下載實(shí)例(多種上傳方式)
- 解決ASP.NET Core Mvc文件上傳限制問題實(shí)例
- asp.net core mvc實(shí)現(xiàn)文件上傳實(shí)例
- ASP.NET Core單文件和多文件上傳并保存到服務(wù)端的方法
- asp.net core集成kindeditor實(shí)現(xiàn)圖片上傳功能
- asp.net core分塊上傳文件示例
- ASP.NET Core實(shí)現(xiàn)多文件上傳
- ASP.NET Core上傳文件到minio的實(shí)現(xiàn)示例
相關(guān)文章
.NET發(fā)送郵件的實(shí)現(xiàn)方法示例
這篇文章主要給大家介紹了關(guān)于.NET發(fā)送郵件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用.net具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06asp.net AutoCompleteExtender的一個(gè)簡(jiǎn)單例子代碼
asp.net AutoCompleteExtender的一個(gè)簡(jiǎn)單例子代碼2009-12-12.NET中讀取Excel文件的數(shù)據(jù)及excelReader應(yīng)用
輕量,快速的C#編寫的庫讀取Microsoft Excel文件,這對(duì)讀取大量excel文件的朋友們很有幫助而且可以學(xué)習(xí)下ExcelDataReader的應(yīng)用,感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02先裝了FRAMEWORK,后裝IIS導(dǎo)致asp.net頁面無法訪問的解決方法
如果先裝了FRAMEWORK,后裝IIS。有可能沒有在IIS中注冊(cè),就會(huì)導(dǎo)致在頁面中無法訪問的情況2012-01-01如何在?ASP.NET?Core?Web?API?中處理?Patch?請(qǐng)求
這篇文章主要介紹了在?ASP.NET?Core?Web?API中處理Patch請(qǐng)求,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05c#實(shí)現(xiàn)根據(jù)網(wǎng)絡(luò)IP顯示地理位置功能示例
通常都會(huì)有類似 注冊(cè)IP和最后登錄IP這兩個(gè)的字段來存儲(chǔ)用戶注冊(cè)時(shí)候的IP地址和最后登錄的IP的地址,現(xiàn)在我們就簡(jiǎn)單的實(shí)現(xiàn)一下如標(biāo)題所示的功能2013-06-06