I got a webSocket comunication, I recieve base64 encoded string, convert it to uint8 and work on it, but now I need to send back, I got the uint8 array, and need to convert it to base64 string, so I can send it. How can I make this convertion?
问题:
回答1:
If your browser has TextDecoder then use that:
var u8 = new Uint8Array([65, 66, 67, 68]); var decoder = new TextDecoder('utf8'); var b64encoded = btoa(decoder.decode(u8));
If you need to support browsers that do not have TextDecoder (currently just IE and Edge), then the best option is to use a TextDecoder polyfill.
If your strings is plain ASCII and not multibyte Unicode/UTF-8 then there are is a simple alternative using String.fromCharCode that should be fairly universally supported:
var u8 = new Uint8Array([65, 66, 67, 68]); var b64encoded = btoa(String.fromCharCode.apply(null, u8));
And to decode the base64 string back to a Uint8Array:
var u8_2 = new Uint8Array(atob(b64encoded).split("").map(function(c) { return c.charCodeAt(0); }));
If you have very large array buffers then the apply may fail and you may need to chunk the buffer (based on the one posted by @RohitSengar). Again, note that this is only correct if your buffer only contains non-multibyte ASCII characters:
function Uint8ToString(u8a){ var CHUNK_SZ = 0x8000; var c = []; for (var i=0; i
回答2:
function Uint8ToBase64(u8Arr){ var CHUNK_SIZE = 0x8000; //arbitrary number var index = 0; var length = u8Arr.length; var result = ''; var slice; while (index
You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.
回答3:
Very simple solution and test for JavaScript!
ToBase64 = function (u8) { return btoa(String.fromCharCode.apply(null, u8)); } FromBase64 = function (str) { return atob(str).split('').map(function (c) { return c.charCodeAt(0); }); } var u8 = new Uint8Array(256); for (var i = 0; i
回答4:
(Decode a Base64 string to Uint8Array or ArrayBuffer with Unicode support)
回答5:
I'll add another solution that works with non-printable ranges. My guess is this is faster than chaining TextEncoder
and btoa
.
var blob = new Blob( [ uint8ArrayBuffer ], { type: "image/jpeg" } ); var imageUrl = URL.createObjectURL( blob );
This is using HTML5 APIs, and so will not work on Node or other JS based servers, of course. You can see a demo here.
回答6:
If all you want is a JS implementation of a base64-encoder, so that you can send data back, you can try the btoa
function.
b64enc = btoa(uint);
A couple of quick notes on btoa - it's non-standard, so browsers aren't forced to support it. However, most browsers do. The big ones, at least. atob
is the opposite conversion.
If you need a different implementation, or you find an edge-case where the browser has no idea what you're talking about, searching for a base64 encoder for JS wouldn't be too hard.
I think there are 3 of them hanging around on my company's website, for some reason...