AlumCloud.Com AlumCloud.Com - 1 year ago 134
C# Question

How to return a bitmap to a browser WebApi

I am making a request to the server "WebApi" using JavaScript from an already loaded document on the client side.

When the server receives the request it builds a bitmap on the fly and returns it back to the client as a .png.

When i read the response on the client side all I get back from the data portion of the .ajax request is an empty string.

How can I read and image requested from a server using WebApi and then set the src attribute of a image on the client side with the new image received from the server?

--WebApi

public HttpResponseMessage Get(int id)
{
ElevationResponse elev = ElevationHelper.GetElevation(id);

Bitmap canvas = ShopDrawing.Elevation.Elevation.GetShopDrawing(elev, true);

var ms = new MemoryStream();
canvas.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

HttpResponseMessage r = Request.CreateResponse();
r.Content = new StreamContent(ms);
r.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return r;
}


--Client

$.ajax(
{
async: true,
url: '/api/drawings?id=' + this.id,
type: 'GET',
contentType: "application/json",
success: function (d, status) {
debugger

}
});

Answer Source

Simply specify '/api/drawings?id=' + this.id as image src attribute.

On the server side, you should reset the memory stream after canvas.Save() so that it will be sent from the beginning. Also, specify the http Content-Length header so that browsers know the total size while downloading:

ms.Position = 0;
r.Content.Headers.ContentLength = ms.Length;

If this does not work, enter the url directly in your browser and enable the developer tools to view the network traffic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download