从字节返回FileResult [] [英] Return a FileResult from a byte[]
问题描述
我正在研究ASP.NET Core API.该API是数据库驱动的.
I am working on an ASP.NET Core API. The API is database driven.
我正在将图像存储在数据库中,我的 ArtistImage.cs
实体如下所示:
I am storing images in the database, my ArtistImage.cs
entity looks like this:
ArtistImage.cs
public class ArtistImage
{
public int Id { get; set; }
public byte[] Data { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? ModifiedAt { get; set; }
public int ArtistId { get; set; }
public Artist Artist { get; set; }
}
如何将 byte []
转换为类似的内容: return File(〜/Images/photo.jpg","image/jpeg");
其中只会为图片服务?
How can I convert a byte[]
to something like: return File("~/Images/photo.jpg", "image/jpeg");
where that would simply serve the image?
我要避免先将字节数组写入本地系统文件.
I want avoid writing the byte array to a local system file first.
我尝试过的事情
我尝试了下面的方法,但是显然,我不能像这样使用 File
.
I have tried the method below, but apparently, I can't use File
like that.
public class ImagesService : IImagesService
{
private readonly DbContext context;
public ImagesService(DbContext context)
{
this.context = context;
}
public async Task<FileResult> GetArtistImageAsync(int imageId)
{
byte[] imageBytes = await context
.ArtistImages
.Where(ai => ai.Id == imageId)
.Select(ai => ai.Data)
.SingleOrDefaultAsync();
return System.IO.File(imageBytes, "image/jpg", "test");
}
}
推荐答案
This appears to be an XY problem. You are mixing up controller helper methods and trying to access them from an unrelated service.
我建议您重构服务以返回字节数组
I would suggest you refactor the service to return the byte array
ImagesService
public Task<byte[]> GetArtistImageAsync(int imageId) {
return context.ArtistImages
.Where(ai => ai.Id == imageId)
.Select(ai => ai.Data)
.SingleOrDefaultAsync();
}
然后让控制器返回FileResult
and then have the controller return the FileResult
控制器
public async Task<IActionResult> SomeAction(....) {
//...
var bytes = await imagesService.GetArtistImageAsync(imageId);
return File(bytes, "image/jpeg");
}
这篇关于从字节返回FileResult []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!