Search code examples
c#asp.netsql-serverhttpdapper

Getting bytes[] image from Database as IFormFile


I am making an API that can upload to and retrieve images from the database. The first part is done - the image gets stored in an IFormFile variable and gets passed to the database as bytes[].

Image model:

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

So this is how I am currently trying to write the GET method. My idea is to get the bytes from the database and convert them into a File that can afterward be visible on a web page.

 [Route("v1/recipe/image/{recipeId}")]
 [HttpGet()]
 public IActionResult GetImage(int recipeId)
 {
     byte[] data;
     try
     {
         using (var con = _connFactory())
         {
             data = con.Query("SELECT Image FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId }).FirstOrDefault();
         }

         return File(new MemoryStream(data), "image/jpeg", "SomeName.jpg");
     }
     catch (Exception exc)
     {
         return BadRequest();
     }
 }

exc looks like:

{"Cannot implicitly convert type 'object' to 'byte[]'. An explicit conversion exists (are you missing a cast?)"}

I don't know whether this code is supposed to be correct or not but data is always null. I also tried the SQL statement (SELECT Image FROM RecipeImage WHERE RecipeId = '140') in SSMS and it's bringing out the correct output:

1]

Is there any other way in which I could achieve what I am trying to do?


Solution

  • You are not telling Dapper what type to expect.

    This should do it:

    using (var con = _connFactory())
    {
        data = con.Query<byte[]>("SELECT Image FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId }).FirstOrDefault();
    }
    

    Personally I would prefer:

    using (var con = _connFactory())
    {
        data = con.QuerySingle<byte[]>("SELECT Image FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId });
    }
    

    which will throw an exception if more or less than one image is found.