在使用asp.net web api core时,以IActionResult的形式返回图像文件的最佳方式是什么? 我尝试了返回base64字符串的方法,它可以正常工作,但不被认为是高效的。 有没有一种方法可以直接将图像文件对象作为IActionResult返回。
在使用asp.net web api core时,以IActionResult的形式返回图像文件的最佳方式是什么? 我尝试了返回base64字符串的方法,它可以正常工作,但不被认为是高效的。 有没有一种方法可以直接将图像文件对象作为IActionResult返回。
Controller
或ControllerBase
的控制器中使用File()
函数的各种重载形式。
例如,你可以这样做:
return File("~/Images/photo.jpg", "image/jpeg");
这里使用了虚拟路径,其他选项包括将其作为字节数组或Stream
给出。如果需要,您还可以将下载文件名作为第三个参数提供。
[Route("getProductImage/v1")]
[HttpGet]
public async Task<IActionResult> getProductImage(GetProductImageQueryParam parammodel)
{
using (HttpClient client = new HttpClient())
{
MNimg_URL = MNimg_URL + parammodel.modelname;
HttpResponseMessage response = await client.GetAsync(MNimg_URL);
byte[] content = await response.Content.ReadAsByteArrayAsync();
//return "data:image/png;base64," + Convert.ToBase64String(content);
return File(content, "image/png", parammodel.modelname);
}
}
在 .NET Core 3.x 中,File
结果被称为 FileContentResult
。
您可以使用带有流或字节格式的返回文件,或者使用其图像路径返回图像。
在MVC控制器的操作方法中,有几种重载方法可用于return File(//parameters);
。
API控制器
[Route("api/[controller]")]
public class FileController : Controller {
//GET api/file/id
[HttpGet("{id}"]
public async Task<IActionResult> GetFile(string id) {
var stream = await {{//__get_stream_here__//}};
var response = File(stream, "application/octet-stream"); // FileStreamResult
return response;
}
}
或者
var imageFileStream = System.IO.File.OpenRead("// image path");
return File(imageFileStream, "image/jpeg");