Reputation: 85
I need to base64 encode the content of a raw PDF (already got the raw content). but i don't know why, but btoa() expect the input to be an ASCII char composed string.
btoa('ééééééé');
>> InvalidCharacterError: String contains an invalid character
Is there any way to convert raw bytes to base64 in javascript without recoding the base64 algo ? (by the way, working for images, and whatever file content)
By advance, Thanks for your answers !
[
Upvotes: 3
Views: 9648
Reputation: 5769
If you are storing contents as Blob
, use the FileReader
object to convert it to data URI, then remove its prefix:
var reader = new FileReader();
reader.onload = function () {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
console.log(b64);
};
reader.readAsDataURL(your_blob);
Another way, if you are storing it as ArrayBuffer
:
// Create a Uint8Array from ArrayBuffer
var codes = new Uint8Array(your_buffer);
// Get binary string from UTF-16 code units
var bin = String.fromCharCode.apply(null, codes);
// Convert binary to Base64
var b64 = btoa(bin);
console.log(b64);
Upvotes: 3