简体   繁体   English

jQuery Img Attr请求获取服务器发送的标头

[英]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). 我想做的是使用jQuery请求图像(在这种情况下为图形)。 In jQuery I'm setting the src attribute on my image which pulls down the graph from the server as expected. 在jQuery中,我在图像上设置了src属性,该属性将按预期从服务器拉下图形。

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

I want to be able to send some Header information down with this request and have jQuery read it. 我希望能够与此请求一起向下发送一些Header信息,并让jQuery读取它。

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. 我的一个朋友建议使用ajax将图像下载到blob,然后将blob写入image标签...不知道如何做到这一点。

Try this for Non IE browsers < 7. For 对于非IE浏览器<7,请尝试此操作。

$.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 将图像转换为base64字符串的代码

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;
  }
}

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);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM