简体   繁体   English

从 model class 以字节为单位从数据库检索图像到 IFormFile 的问题

[英]Issue retrieving Image in bytes from Database to IFormFile from model class

After creating a POST method for my API that allows me to upload images to the database where I hold them as bytes, I wanted to create a GET method that will allow me to get their information and eventually show them on a web page.在为我的 API 创建了一个POST方法后,该方法允许我将图像上传到我保存为字节的数据库中,我想创建一个GET方法,该方法将允许我获取它们的信息并最终在 web 页面上显示它们。

My model class looks like this:我的 model class 看起来像这样:

public class Image
{
    public int recipeId { get; set; }
    public string format { get; set; }
    public string description { get; set; }
    public IFormFile image { get; set; }
}

IFormFile image is the image that gets uploaded from the front-end and gets converted using MemoryStream to fill the database like this: IFormFile image是从前端上传并使用MemoryStream转换以填充数据库的图像,如下所示:

在此处输入图像描述

This being said, below is my GET method:话虽这么说,下面是我的GET方法:

[Route("v1/recipe/image/{recipeId}")]
[HttpGet()]
public Image GetImage(int recipeId)
{
    using (var con = _connFactory())
    {
        con.Open();
        return con.Query<Image>("SELECT * FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId }).FirstOrDefault();
    }
}

But I am getting the following error:但我收到以下错误:

System.Data.DataException: 'Error parsing column 3 (Image=System.Byte[] - Object)' System.Data.DataException: '解析第 3 列时出错 (Image=System.Byte[] - Object)'

InvalidCastException: Unable to cast object of type 'System.Byte[]' to type 'Microsoft.AspNetCore.Http.IFormFile'. InvalidCastException:无法将“System.Byte []”类型的 object 转换为“Microsoft.AspNetCore.Http.IFormFile”类型。

I understand what is going bad here, but I could not find any way around this.我知道这里出了什么问题,但我找不到任何解决方法。 The only solution that I thought of was creating another model class for Image which instead of IFormFile has byte[] , but I was wondering if there's a better way of solving this problem.我想到的唯一解决方案是为 Image 创建另一个 model class 而不是IFormFilebyte[] ,但我想知道是否有更好的方法来解决这个问题。

That's because you can't cast a Byte array to IFormFile .那是因为您不能将 Byte 数组转换为IFormFile

If you want to get an Image object, you'd first load the Byte array into a MemoryStream then call Image.FromMemoryStream(stream)如果要获取图像 object,首先将字节数组加载到MemoryStream中,然后调用Image.FromMemoryStream(stream)

using (var ms = new MemoryStream(byteArrayIn))
{
    return Image.FromStream(ms);
}

You might want to consider adding an additional property into your model that returns the Image type, and load the value into it when the byte array is being set ie inside the setter for the byte[] .您可能需要考虑在返回Image类型的 model 中添加一个附加属性,并在设置字节数组时将值加载到其中,即在byte[]的设置器中。

public class Image
{
    public int recipeId { get; set; }
    public string format { get; set; }
    public string description { get; set; }
    private byte[] _image { get; set; }
    public byte[] image { get { return _image; } set { 
        _image = value; 
        using(var ms = new MemoryStream(byteArrayIn)) ...
            imageFile = Image.FromStream(ms);...
    }
    public Image imageFile { get; set; }
}

One way would be to map the properties manually一种方法是手动到 map 属性

using (var con = _connFactory())
{
    con.Open();
    return con.Query("SELECT * FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId })
                .Select(x => new Image() 
                {
                    recipeId = x.RecipeId,
                    format = x.Format,
                    description = x.Description,
                    image = new FormFile(new MemoryStream(x.Image), 0, x.Image.Length, null, "MyFile." + x.Format, "")
                })
                .FirstOrDefault();
}

But probably you want to send the file alone if you want to display it on the web.但如果您想在 web 上显示文件,您可能想单独发送文件。 Try navigating to the v1/recipe/image/xxx endpoint in the browser to see if the image loads.尝试导航到浏览器中的 v1/recipe/image/xxx 端点以查看图像是否加载。

[Route("v1/recipe/image/{recipeId}")]
[HttpGet()]
public async Task<IActionResult> GetImage(int recipeId)  
  {  
      var data = await con.QueryAsync<byte[]>("SELECT Image FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId }) 

      return File(new MemoryStream(data), "image/jpeg", "SomeName.jpg");  
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM