.NetCore 接口返回图片文件
本文实例环境及版本 .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"); }
才疏学浅,相关文档等仅供自我总结,如有相关问题可留言交流谢谢。