簡單介紹ASP.NET Core實現檔案上傳和下載
導讀 | 這篇文章主要為大家詳細介紹了ASP.NET Core實現檔案上傳和下載,文中示例程式碼介紹的非常詳細,具有一定的參考價值,感興趣的小夥伴們可以參考一下 |
本文例項為大家分享了ASP.NET Core實現檔案上傳和下載的具體程式碼,供大家參考,具體內容如下
一、檔案上傳
1.1 獲取檔案字尾
/// < summary> /// 獲取檔案字尾 /// < /summary> /// < param name="fileName">檔名稱< /param> /// < returns> public async static TaskGetFileSuffixAsync(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 TaskUploadFileAsync(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<1list> UploadFilesAsync(IFormFileCollection files, string fold) { string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Listmessages = 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, ILoggerlogger) { _env = env; _logger = logger; } /// < summary> /// 協議上傳附件 /// < /summary> /// < param name="file">< /param> /// < returns>< /returns> [HttpPost("upload")] public async TaskUploadProtocolFile([FromForm] IFormFile file) { return await UploadFileAsync(file, "ManageProtocol"); } }
二、檔案下載
2.1 獲取ContentType屬性
/// < summary> /// 獲取檔案ContentType /// < /summary> /// < param name="fileName">檔名稱< /param> /// < returns>< /returns> public async static TaskGetFileContentTypeAsync(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, ILoggerlogger) { _env = env; _logger = logger; } /// < summary> /// 下載附件 /// < /summary> /// < param name="fileName">檔名稱 /// < returns>< /returns> [HttpGet("download")] public async TaskDownload([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()); } } }
原文來自:
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69955379/viewspace-2909657/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 實現簡單的csv檔案上傳和bootstrap表格的下載boot
- 前端實現檔案下載和拖拽上傳前端
- ASP.NET Core 檔案上傳ASP.NET
- Feign實現檔案上傳下載
- asp.net 檔案上傳和下載管理原始碼ASP.NET原始碼
- js實現的動態載入css檔案簡單介紹JSCSS
- Jsp+Servlet實現檔案上傳下載(一)--檔案上傳JSServlet
- 利用Wireshark和OSS的API文件簡單實現上傳和下載API
- java實現sftp檔案的上傳下載JavaFTP
- SpringMVC實現檔案上傳&下載(2)SpringMVC
- 檔案上傳和下載功能
- 實現js檔案動態載入的幾種方式簡單介紹JS
- SpringMVC檔案上傳下載(單檔案、多檔案)SpringMVC
- python寫的FTP簡單上傳下載檔案薦PythonFTP
- ASP.NET中檔案上傳下載方法集合ASP.NET
- vue實現Excel檔案的上傳與下載VueExcel
- JavaWeb之實現檔案上傳與下載工具JavaWeb
- JavaWeb之實現檔案上傳與下載元件JavaWeb元件
- JavaWeb之實現檔案上傳與下載示例JavaWeb
- Spring Boot + thymeleaf 實現檔案上傳下載Spring Boot
- 動態載入js檔案簡單介紹JS
- 檔案上傳下載
- 檔案管理簡單介紹
- PHP實現單檔案、多檔案上傳 封裝 物件導向實現檔案上傳PHP封裝物件
- 在Oracle中存取BLOB物件實現檔案的上傳和下載Oracle物件
- Java實現上傳檔案到Oracle及從Oracle下載檔案JavaOracle
- 使用Vue+go實現前後端檔案的上傳下載,csv檔案上傳下載可直接照搬VueGo後端
- JavaWeb之實現檔案上傳與下載外掛JavaWeb
- JavaWeb之實現檔案上傳與下載原始碼JavaWeb原始碼
- JavaWeb之實現檔案上傳與下載例項JavaWeb
- React中使用fetch實現檔案上傳下載React
- 教你如何實現c#檔案上傳下載功能C#
- jQuery動態載入js檔案簡單介紹jQueryJS
- js動態載入js檔案簡單介紹JS
- 檔案上傳原理和實現
- springCloud 微服務通過minio實現檔案上傳和檔案下載介面SpringGCCloud微服務
- 單個檔案上傳和批量檔案上傳
- 簡單實現TCP下的大檔案高效傳輸TCP