Get Image using jQuery.ajax() and decode it to base64

后端 未结 2 740
轮回少年
轮回少年 2020-12-05 14:06

What i want to do:

HTTP-GET an image (jpeg) using jQuery.ajax() from a basic-auth secured server. it seems like i get some data of the image, it must be binary. i wa

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 14:46

    First of all, according to Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python add the correct mimetype to the Ajax call:

     $.ajax({
                url: "someurltoajpeg",
                type: "GET",
                headers: {
                    "Authorization" : "Basic " +  btoa("user:pw")
                },
                xhrFields: {
                    withCredentials: true
                },
                mimeType: "text/plain; charset=x-user-defined"
            }).done(function( data, textStatus, jqXHR ) {
                $("#image").attr('src', 'data:image/jpeg;base64,' + base64encode(data));
            }).fail(function( jqXHR, textStatus, errorThrown ) {
                alert("fail: " + errorThrown);
            });
    

    Then use base64Encode function described instead then the btoa:

    function base64Encode(str) {
            var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var out = "", i = 0, len = str.length, c1, c2, c3;
            while (i < len) {
                c1 = str.charCodeAt(i++) & 0xff;
                if (i == len) {
                    out += CHARS.charAt(c1 >> 2);
                    out += CHARS.charAt((c1 & 0x3) << 4);
                    out += "==";
                    break;
                }
                c2 = str.charCodeAt(i++);
                if (i == len) {
                    out += CHARS.charAt(c1 >> 2);
                    out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                    out += CHARS.charAt((c2 & 0xF) << 2);
                    out += "=";
                    break;
                }
                c3 = str.charCodeAt(i++);
                out += CHARS.charAt(c1 >> 2);
                out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                out += CHARS.charAt(c3 & 0x3F);
            }
            return out;
        }
    

    bye

提交回复
热议问题