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 posed 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 !
[
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 posed 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 !
[
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 3, 2018 at 18:05 w2dw2d 851 silver badge7 bronze badges 4- "already got the raw content" - care to show how exactly? – georg Commented Dec 3, 2018 at 18:32
- I don't want to display the content, i want to base64 encode it, in order to send the encoded content on severals microservices – w2d Commented Dec 4, 2018 at 9:54
-
Georg wants to know how you read/load the raw content? This is why the plete code snippet will be very useful. Or, at least, tell us how you store bytes (for example, as
ArrayBuffer
orBlob
)? – Victor Commented Dec 4, 2018 at 10:53 - I store (uncasted input) the content in utf8 string buffer. I also tried in a blob, unsuccessfully. Here is a part of my input : ��D��A�-�z�� A�D<-�z��eB�B�E � ``` import base64 print(base64.b64encode("��D��A�-�z�� A�D<-�z��eB�B�E �")) # result should be 77+977+9RO+/ve+/vUHvv70t77+9eu+/ve+/vSBB77+9RDwt77+9eu+/ve+/vWVC77+9Qu+/vUUg77+9``` (modifié) – w2d Commented Dec 4, 2018 at 13:09
1 Answer
Reset to default 3If 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);