简体   繁体   中英

how convert binary data in base64 from couchdb attachments

I try to get binary data from my couchdb server. But I can use them. The response contain a string that rapresent binary data, but if I try to code in base64 with the function btoa, the function give me this error:

Uncaught InvalidCharacterError: 'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.

I know that I can get data directly coded in base64, but I don't want.

    $.ajax({
        url: "http://localhost:5984/testdb/7d9de7a8f2cab6c0b3409d4495000e3f/img",
        headers: {
                Authorization: 'Basic ' + btoa("name:password"),
        },
        success: function(data){
            /*console.log(JSON.parse(jsonData));
            console.log(imageData);*/
            document.getElementById("immagine").src = "Data:image/jpg;base64," + btoa(data);
            console.log(data);
        }
    });

any idea?

Start with the knowledge that each char in a Base64 String

var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');

represents a Number , specifically from 0 to 63 . Next, consider that this range of numbers is all the numbers you can write with 6 bits and that we normally think about binary data in bytes which are 8 bits long.

So now we can conclude, the transformation we which to achieve is 8 bit integers to 6 bit integers, which looks a bit like this

xxxxxx xxyyyy yyyyzz zzzzzz

where each letter describes which byte the bit is in, and the spaces describe the breaks between the 6 bit integers.

Once we have the 6 bit number, we can simply transform to the char and finally add = signs if we need to indicate the number of bytes was not a multiple of 3 (and they're not simply 0 )

So how do we do this?

var arr8 = 'foobar'; // assuming binary string

var i, // to iterate
    s1, s2, s3, s4, // sixes
    e1, e2, e3, // eights
    b64 = ''; // result
// some code I prepared earlier
for (i = 0; i < arr8.length; i += 3) {
    e1 = arr8[i    ];
    e1 = e1 ? e1.charCodeAt(0) & 255 : 0;
    e2 = arr8[i + 1];
    e2 = e2 ? e2.charCodeAt(0) & 255 : 0;
    e3 = arr8[i + 2];
    e3 = e3 ? e3.charCodeAt(0) & 255 : 0;
    // wwwwwwxx xxxxyyyy yyzzzzzz
    s1 =                     e1 >>> 2 ;
    s2 = ((e1 &  3) << 4) + (e2 >>> 4);
    s3 = ((e2 & 15) << 2) + (e3 >>> 6);
    s4 =   e3 & 63                    ;
    b64 += chars[s1] + chars[s2];
    if (arr8[i + 2] !== undefined)
        b64 += chars[s3] + chars[s4];
    else if (arr8[i + 1] !== undefined)
        b64 += chars[s3] + '=';
    else
        b64 += '==';
}
// and the result
b64; // "Zm9vYmFy"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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