近排做一个项目,需要用到API返回图片和文件,网上看了几种方法,记录一下
1.文件流的方式
public async Task<IActionResult> ShowImage() { using (var sw = new FileStream(file_path,FileMode.Open)) { var bytes = new byte[sw.Length]; sw.Read(bytes, 0, bytes.Length); sw.Close(); return new FileContentResult(bytes, "image/jpeg"); } }
2.直接返回文件
public async Task<IActionResult> ShowImage() { return PhysicalFile(@"c:\404.jpg", "image/jpeg"); }