0

I try to get images that match with the parameter value but it returns only a single image(first image in DB). my images are saved as binary in DB

    [HttpGet]
    [AllowAnonymous]
    [Route("api/GetImages")]
    public HttpResponseMessage GetImages(int productId)
    {

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        
        IEnumerable<ProductImage> files = _context.ProductImages.Where(p => p.ProductId == productId);
        foreach (var item in files)
        {
            response.Content = new ByteArrayContent(item.Image);
            response.Content.Headers.ContentLength = item.Image.LongLength;

            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = item.Name;

            response.Content.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
        }
        return response;
    }
ashfan
  • 1
  • 3

1 Answers1

0

ProductImage file = _context.ProductImages.FirstOrDefault(p => p.ProductId == producId);

the way this line is written, using FirstOrDefault, will only ever return the first ProductImage it finds matching the productId.

I believe what you're looking for should be more like

IEnumerable<ProductImage> files = _context.ProductImages.Where(p => p.ProductId == producId);

The for loop you have written will also not work how you expect it, if you try and fetch productId 100, it will loop 100 times, setting the content of your response to the same picture 100 times. After re-reading and noticing the return at the end of your loop, it will always stop after the first iteration.

You'll probably want to do a foreach loop over files and add them to your response with something like this: What's the best way to serve up multiple binary files from a single WebApi method?

Ced
  • 1,117
  • 1
  • 8
  • 16
  • Thanks for ur help. I used foreach loop and I'm still getting 1 image. I'll update the question with my current code. – ashfan Jul 16 '21 at 12:18
  • You're still resetting the response.Content each loop, the answer I linked shows you should be creating a MultipartContent object outside of the loop, populating it inside the loop, then set your response.Content to the MultipartContent object after your loop – Ced Jul 16 '21 at 21:33