2

Images are generated dynamically with a handful of user input parameters. I'm able to successfully produce the image via GET, by writing to Response.OutputStream

$('#myImage').attr('src', 'Images/GetImage?param1=value1&param2=value2');

There are several additional parameters. But, how can I accomplish this with a POST? I thought I might use $.ajax and base64 encode the Image, but it doesn't quite work.

$.ajax({
    url: 'Images/GetImage64',
    type: 'POST',
    data: { param1: 'value1', param2: 'value2' },
    success: function (data) {
        //$('#myImage').attr('src', data); 
        $('#myImage').attr('src', 'data:image/png;base64, ' + data);
    }
});

Chrome dev tools shows an ajax (XHR) POST to /Images/GetImage64 with a text/plain response. The content looks like the PNG generated on the server. However, another "Other" request is made with the URL below, and I have no idea what's going on

data:image/png:base64, [binary]

On the server, I'm returning an ImageResult : ActionResult that overrides ExecuteResult and response with base64 encoded image.

public override void ExecuteResult(ControllerContext context)
{
    context.HttpContext.Response.Clear();
    context.HttpContext.Response.ContentType = "text/plain";
    context.HttpContext.Response.BinaryWrite(GetBase64Image(Image));
}
David Fox
  • 10,603
  • 9
  • 50
  • 80
  • If you're getting another request with `data...` as the url, then for some reason chrome isn't allowing you to dynamically set a data url as the src for the image. It's doing a request for `http://example.com/data:image/....` – Marc B Aug 12 '11 at 19:47
  • @Marc B Firefox 5 and IE9 behaves similarly. Regardless, my image doesn't render – David Fox Aug 12 '11 at 19:51
  • This [blog post](http://onwebdev.blogspot.com/2011/03/jquery-data-urls-and-ajax.html) seems to indicate it should work, though it's using gifs instead of pngs. Maybe capture the base64 data try decoding it back to binary, see if it's bitwise identical. maybe some corrupted output before the actual png data breaks the 'src' setting. – Marc B Aug 12 '11 at 19:56
  • @Marc B That wasn't exactly it, but your suggestion helped me find the problem. I inadvertently returned the byte array from my `Image` object instead of the base64 encoded string of data – David Fox Aug 12 '11 at 20:06

1 Answers1

1

Might be jQuery's fault. Try forcing jQuery to treat the result as plain text with dataType: 'text':

$.ajax({
    url: 'Images/GetImage64',
    type: 'POST',
    dataType: 'text',
    data: { param1: 'value1', param2: 'value2' },
    success: function (data) {
        $('#myImage').attr('src', 'data:image/png;base64,' + data);
    }
});

Edit: Nevermind, wasn't that.

Laurence
  • 1,673
  • 11
  • 16
  • Thanks, but it was my encoding that screwed it up--I wasn't sending the correct byte array to the client – David Fox Aug 12 '11 at 20:07