.NetCore 介面返回圖片檔案
阿新 • • 發佈:2022-12-13
本文例項環境及版本 .NetCore3.1
1、返回圖片檔案流
/// <summary> /// 返回圖片檔案流 /// </summary> /// <returns></returns> [HttpGet("GetFileInfo2")] public FileContentResult GetFileInfo2() { using (var sw = new FileStream("C:/YundiApp/FileData/images/20220617/2022061710060716957376.jpg", FileMode.Open)) { var contenttype =GetContentTypeForFileName("C:/YundiApp/FileData/images/20220617/2022061710060716957376.jpg"); var bytes = new byte[sw.Length]; sw.Read(bytes, 0, bytes.Length); sw.Close(); return new FileContentResult(bytes, contenttype); } }public static string GetContentTypeForFileName(string fileName) { //獲取檔案字尾 string ext = Path.GetExtension(fileName); using (Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext)) { if (registryKey == null) return null; var value = registryKey.GetValue("Content Type"); return value?.ToString(); } }
2、直接返回圖片檔案
/// <summary> /// 返回圖片 直接返回圖片檔案 /// </summary> /// <returns></returns> [HttpGet("GetFile")] public IActionResult GetFile() {return PhysicalFile(@"C:/YundiApp/FileData/images/20221017/202210171716154635.jpeg", "image/jpeg"); }
才疏學淺,相關文件等僅供自我總結,如有相關問題可留言交流謝謝。