Chris Kooken
Chris Kooken

Reputation: 33870

JQuery Img Attr request get headers sent by the server

What I want to do is use jQuery to request an image (a graph in this case). In jQuery I'm setting the src attribute on my image which pulls down the graph from the server as expected.

$("#graphImage").attr("src", graphUrl);

I want to be able to send some Header information down with this request and have jQuery read it.

How can I do this. A friend of mine recommended downloading the image using ajax to a blob then writing the blob to the image tag...not sure how this can be done.

Upvotes: 2

Views: 2141

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this for Non IE browsers < 7. For

$.ajax({
  url: graphUrl,//This will be a page which will return the base64 encoded string
  headers: {},//Pass the required header information
  success: function(response){
     $("#graphImage").attr("src", response);
  }
});

Code to convert image to base64 string

public string ImageToBase64(Image image, 
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Upvotes: 2

wightnoise
wightnoise

Reputation: 73

I don't know about reading the response to load an image but pulling the response headers is straight forward.

jQuery.ajax({
  url: '/img/foo.gif',
  complete: function (jqXHR, textStatus) {
    var h = jqXHR.getResponseHeader('Content-Type');
    alert(h);
  }
});

Upvotes: 2

Related Questions