Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Images from WebApi

I am making a Web Api and I need to return multiple images to the client. I am currently using a Base64 string for each image but this results in each request taking far too long. Is there a better, more efficient way of returning images?

This is the code I am 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;
    }
like image 527
Wade Ferreira Avatar asked Apr 21 '16 12:04

Wade Ferreira


1 Answers

If the endpoint returns json, then there is no other way, beyond base64, how to embed binaries within the response. But it is definitely a bad idea due to the performance issues. May be for some icons it would be ok, but for larger images its not suitable.

So the best solution here, is to return the url to the image. And the client will make further request to get raw bytes for the image.

Also worth to mention, the image url can not only be the path to the static file, but also a path to some webapi endpoint, which, for instance, gets the image bytes by the resource id and sends the client raw binary back, and not a json string.

like image 186
tenbits Avatar answered Sep 21 '22 23:09

tenbits