I have the following webapi method
public HttpResponseMessage GetImage()
{
string imgUri = HttpContext.Current.Server.MapPath("~/Images/htmllogo.png");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(imgUri, FileMode.Open));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return response;
}
I also have the following html
<div><button id="loadImage">Load</button></div>
<div id="divImageHolder"></div>
I am using jquery's Ajax method to retrieve my image like this:
$("#loadImage").click(function () {
var options = {};
options.url = "api/mywebapi/GetImage";
options.type = "GET";
//options.dataType = "image/png";
options.contentType = "image/png";
options.success = function (results) {
var imag = "<img " + "src='" + results + "'/>";
$("#divImageHolder").html(imag);
};
options.error = function (jqXHR, textStatus, errorThrown)
{
console.log(errorThrown);
};
$.ajax(options);
});
What I see after clicking the button is 'binary garbage' in divImageHolder div. No image is being displayed
I have tried adding "data:image/png;base64" to src property before the result but that didn't work. I think the reason is that base64 is text encoding but what I am receiving is binary data.
If I use Json and convert the image into base64 encoding (in the web api method) then it works fine however I couldn't manage to get it to work with binary i.e. my web api method is returning StreamContent.
options.dataType is commented out on purpose because it doesn't accept anything but json. If I uncommented it, I will get an error. The error is "No conversion from text to image/png" but if I leave it commented out I manage to get to success method where I can see the binary result
Thank you
Sul