【问题标题】:Display image in html which is returned as a MIME media type from an ajax call以 html 格式显示图像,该图像作为 ajax 调用的 MIME 媒体类型返回
【发布时间】:2014-10-07 12:15:16
【问题描述】:

我正在尝试以 PNG 格式显示图像(它作为 MIME 媒体类型 image/png 从以下代码返回)。是否需要以某种方式保存?:

      $.ajax({
        type: "GET",
        url: url + "/api/image/",
        contentType: "image/png",
        async: false
      })
      .done(function(msg) {
        // msg IS THE MIME MEDIA TYPE PNG IMAGE
        // HOW DO I DISPLAY THIS IMAGE INSIDE AN HTML PAGE?
      })
      .fail(function(msg) {
        // failing is okay for image, just ignore it
      });

【问题讨论】:

    标签: jquery html ajax png mime


    【解决方案1】:

    这是一个使用纯 Javascript (fiddle) 的解决方案:

    HTML

    <div style="background-color: #4679bd; padding: .5em;">
        <img id="image"/>
    </div>
    

    Javascript

    var request = new XMLHttpRequest();
    request.open('GET','http://fiddle.jshell.net/img/logo.png', true);
    request.responseType = 'arraybuffer';
    request.onload = function(e) {
        var data = new Uint8Array(this.response);
        var raw = String.fromCharCode.apply(null, data);
        var base64 = btoa(raw);
        var src = "data:image/jpeg;base64," + base64;
    
        document.getElementById("image").src = src;
    };
    
    request.send();
    

    它使用Uint8ArrayresponseType 属性XMLHttpRequest Level 2,因此您的跨浏览器里程可能会有所不同。我只在最新版本的 Firefox 和 Chrome 中进行了测试。

    就 JQuery 解决方案而言,我发现了很多 discussion 和一些 extensions,但到目前为止还没有“官方”。

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 1970-01-01
      • 2017-03-04
      • 2011-05-11
      • 2011-09-23
      • 2019-09-26
      • 2014-04-07
      • 2017-09-12
      相关资源
      最近更新 更多