Display image in src tag with response text not base64

后端 未结 2 881
长情又很酷
长情又很酷 2020-12-21 14:18

I have a POST request that is returning an image as a gif. As far as I can tell the response is not base64 encoded text. So how can I assign the image to the src tag of an i

2条回答
  •  庸人自扰
    2020-12-21 15:06

    Thanks to the answer from @xchg.ca, I was able to do this by jquery ajax call:

    $.ajax({
      type: "GET",
      url: "imageURL",
      beforeSend: function (xhr) {
        xhr.overrideMimeType('text/plain; charset=x-user-defined');
      },
      success: function (result, textStatus, jqXHR) {       
        if(result.length < 1){
            alert("The thumbnail doesn't exist");
            $("#thumbnail").attr("src", "data:image/png;base64,");
            return
        }
    
        var binary = "";
        var responseText = jqXHR.responseText;
        var responseTextLen = responseText.length;
    
        for ( i = 0; i < responseTextLen; i++ ) {
            binary += String.fromCharCode(responseText.charCodeAt(i) & 255)
        }
        $("#thumbnail").attr("src", "data:image/png;base64,"+btoa(binary));
      },
      error: function(xhr, textStatus, errorThrown){
        alert("Error in getting document "+textStatus);
      } 
    });
    

提交回复
热议问题