Nicros
Nicros

Reputation: 5183

Set image src from ajax post to rest api

Is this possible? My ajax call looks like this:

$.ajax( {
    type: "POST",
    url: "/reporter/api/image/getimage/",
    data: { "": httpNonAccessibleFilePath },
    success: function ( imageData ) {
        $( "#imagecontent" ).append( '<img src="' + imageData + '" />' );
    }
} );

And on my Web.API side:

[HttpPost]
public HttpResponseMessage GetImage([FromBody]string serverPath)
{
    HttpResponseMessage response = new HttpResponseMessage();
    if (serverPath != null)
    {
        FileInfo fileInfo = new FileInfo(serverPath);
        if (fileInfo.Exists)
        {
            response.Content = new StreamContent( fileInfo.OpenRead() );
            response.Content.Headers.ContentType = new MediaTypeHeaderValue( "image/png" );
        }
    }

    return response;
}

All the bits are wired up okay, i.e. I can hit the service and it returns data... but I don't see any images. What am I missing here?

Upvotes: 2

Views: 16406

Answers (3)

a better oliver
a better oliver

Reputation: 26828

Let me suggest an alternative solution. If you would / could make your API accept GET calls then things would be much easier:

var $img = $('<img/>', {
             src: "/reporter/api/image/getimage/?path=" + httpNonAccessibleFilePath
           });   
$( "#imagecontent" ).append( $img);

No AJAX call needed.

Upvotes: 2

Kiruse
Kiruse

Reputation: 1743

As far as I see, you are sending the file contents in response to the AJAX request. As @skuntsel pointed out in his comment, the src attribute must point to a URI. However, there is a solution to this. Have a look at the data: URI scheme. It does exactly what you are looking for, just needs a little more information.

It would look like this, since you're using PNG:

$('#imagecontent').append('<img src="data:image/png;base64,' + imageData + '" />');

See Data: Format on the same Wikipedia article. Obviously this will work only for browsers that support it... it's quite a young technique.

Upvotes: 3

skuntsel
skuntsel

Reputation: 11742

You need to return an URL pointing to image location, which can be your server method producing images.

Basically, you reverted the logics of how img tag works: src of img element must point to a location from where the web browser will download the image. It is not the server that will send the image content to the img.

What needs to be done, thus, is to return URL like /dynamic-images/image-1.jpg and intercept requests on that path so that they'd return actual content.

Upvotes: 3

Related Questions