Web Api 2 - How to return an image (MemoryStream from Azure Storage) from a HTTPGET without saving to disk?
19,727
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
Author by
Terje Nygård
Updated on June 23, 2022Comments
-
Terje Nygård almost 2 years
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 ? });
-
Terje Nygård almost 10 yearsThanks a bunch for this :) Just what i needed!
-
gaurav bhavsar over 8 yearsI am using web API and oauth, so when I use this
<img src="/api/PhotoSubmit/GetPhoto/2232" />
because token is not set in get request, can you now how can I display image ? -
Ty H. over 8 yearsI'm not sure how you might use oath in this case, it may be possible. What I might do to get it done quick and easy is to bypass oath for that Action using the [AllowAnonymous] attribute, then add a parameter for an auth token... and pass that token via query string. <img src="/api/PhotoSubmit/GetPhoto/2232?token=SdLK3424ksflS" />
-
Danny Ellis Jr. over 7 yearsI know this is old, but this isn't working for me. Could someone provide a more complete example with the appropriate server-side code?