Return images from WebApi

I am making web api and I need to return multiple images to the client. I am currently using a Base64 string for each image, but this leads to the fact that each request takes too much time. Is there a better and more efficient way to return images?

This is the code I'm using:

Controller:

public LearningUnits GetLearningUnits([FromODataUri]Guid key) { var record = db.LearningUnits.SingleOrDefault(inst => inst.LearningUnitId == key); record.ImageURLPath = ImageHandler.ImageToByteArrayFromFilePath(record.ImageURLPath); return record; } 

ImageToByteArray Method:

  public static string ImageToByteArrayFromFilePath(string imagefilePath) { byte[] imageArray = File.ReadAllBytes(imagefilePath); string baseImage = Convert.ToBase64String(imageArray); return baseImage; } 
+6
source share
2 answers

The solution is to use media formats, so when the web API is requested with a specific type, you will get the actual binary stream of a specific type.

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

This is a standard RESTful template; you have the same url, but if you want to write JSON data for the data, you accept -type: application / json, but you change your MIME request type to image / png or something similar when you want, to this type of material.

More details can be found here: How to provide custom format formats for OData Api

Odata also implicitly supports it here: https://msdn.microsoft.com/en-us/library/system.web.http.odata.formatter.odatamediatypeformatter(v=vs.118).aspx

0
source

If the endpoint returns json, then there is no other way than base64 how to embed binaries in the response. But this is definitely a bad idea due to performance issues. Maybe for some icons this will be fine, but for large images this is not suitable.

So, the best solution here is to return the URL to the image. And the client will request raw bytes for the image.

It is also worth mentioning that the image url can be not only the path to the static file, but also the path to some webapi endpoint, which, for example, receives bytes of the image using the resource identifier and sends the client binary back, and not the json string.

+1
source

All Articles