Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api 2 - How to return an image (MemoryStream from Azure Storage) from a HTTPGET without saving to disk?

I'm using Web Api 2 with C# and Azure, and having issues with how to return the image (base from Memorystream) for displaying on the page...

Here is my Controller HTTPGET

[Route("api/PhotoSubmit/GetPhoto/{id}")]
    [HttpGet]
    public HttpResponseMessage GetPhotoById(int id)
    {
        StorageServices storage = new StorageServices();
        MemoryStream ms = storage.DownloadBlob(id);
        // return what ?
    }

Here is the beginning of the servicecall :

$http({
            method: 'GET',
            url: 'api/PhotoSubmit/GetPhoto/' + $routeParams.id,
            accept: 'application/json'
        })
        .success(function(result) {
        // How do i handle the result and what HTML should i use ? <img ?
    });
like image 848
Terje Nygård Avatar asked Jul 27 '14 20:07

Terje Nygård


People also ask

How do I get image results back from Web API?

It's better to use the File method overload which accepts a stream, this way you don't to load the picture into the servers memory before sending it. FileStream stream = File. Open(@"E:\\Test. jpg"); return File(stream, "image/jpeg"); or even easier: return PhysicalFile("@E:\\Test.

How can I return images from Web API in asp net?

In order to return images stored directly in a SQL Server database from an ASP.NET Web API you need to create a Get() method that returns HttpResponseMessage. The Content property of the HttpResponseMessage class represents the binary image data associated with an image.

Can we return file result from API?

Let's assume, we have a requirement to send a file based on the file type provided to the service request. For example, when we send the file type as PDF, service will return PDF file if we send Doc, service will return Word document. (I have taken this sample to cover all types of files).


1 Answers

From the client side you don't need to use $http. You can simplify the process by using plain old HTML...

<img src="/api/PhotoSubmit/GetPhoto/2232" />

For dynamic images use JQuery like this...

$('#ImageLocation').html('<img src="/api/PhotoSubmit/GetPhoto/' + intID + '" />');

The web browser will automatically do the work of making an HTTP Request for the image, saving you all the complexity.

On the server side, you can use a process like these to load the file and stream it to the client. It's important that the Server code return the correct MIME type such as...

context.Response.ContentType = "image/png";

Resources:

ASP .Net Web API downloading images as binary

...and...

Display Image using ashx Handler

like image 167
Ty H. Avatar answered Oct 12 '22 12:10

Ty H.