使用 .Net Core 和 Angular 8 从数据库中获取图像(二进制数据)

Get Image(Binary Data) from database with .Net Core and Angular 8

我将图像作为二进制数据存储在数据库中,我想 return 此图像供客户端显示它们,但问题是我编写的代码 return json 数据不是图像,我怎么能 return 图像作为.NET Core 3.1 中客户端的图像 Angular 8

//note document是我图片的那一栏 这是我的代码:

public async Task<dynamic> GetImage(int id)
        {

            string imageBase64Data =Convert.ToBase64String(_repository.Get(id).document);
            string imageDataURL =string.Format("data:image/jpg;base64,{0}",imageBase64Data);
           
            return imageDataURL;
        }

我正在使用 ABP 框架,我的 class 是 ApplicationService Base Class

我从服务器端 (.Net Core ) 找到它我使用了 FileStreamResult 这将 return 一个 link 使您能够下载文件或者您可以使用 FileContentResult 直接 return 文件

//myImage.document is a byte[]
public async Task<FileStreamResult> GetDoc(int id)
 {
            var myImage = await _repository.GetAsync(id);
            var stream = new MemoryStream(myImage.document);
            
            return new FileStreamResult(stream, "image/jpeg" /*chnage this based on your image type */ )
            {
                FileDownloadName = "test.jpeg"
            };
           
        }

到目前为止,我的印象是为 ApplicationService 生成的 APB 动态 Api 控制器没有构建 Api 操作的约定 returning FileStreamResult-s。

因此,为了从基于 Api 的 APB 下载文件,我会为此手动创建控制器,注入所需的服务,该服务将 return Stream 或 byte[] 数组。

[Route("api/[controller]/[action]")]
public class ImageController: AbpController
{    
    private readonly IImageStore _imageStore;

    public ImageController(IImageStore imageStore)
    {
        _imageStore = imageStore;
    }

    [HttpGet]
    [FileResultContentType("image/jpeg")]
    public async Task<FileStreamResult> GetImageStream(string imageId)
    {
        Stream imageStream = await _imageStore.GetImage(imageId);
        imageStream.Seek(0, SeekOrigin.Begin);
        
        var contentDisposition = new ContentDispositionHeaderValue("attachment");
        contentDisposition.SetHttpFileName($"{imageId}.jpg");
        Response.Headers.Add(HeaderNames.ContentDisposition, contentDisposition.ToString());
        
        return new FileStreamResult(imageStream, "image/jpeg");
    }
}

请注意一个重要的属性,以使其与 nswag FileResultContentType 一起工作。有关详细信息,请参阅此 post :

  • What is the correct way to download a file via the NSwag Code Generator (angular 2 typescript)