近排做一個項目,需要用到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"); }