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

泪湿孤枕 提交于 2019-12-23 08:39:37

问题


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 ?
    });

回答1:


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



来源:https://stackoverflow.com/questions/24985536/web-api-2-how-to-return-an-image-memorystream-from-azure-storage-from-a-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!