3

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 !

[enter image description here

4
  • "already got the raw content" - care to show how exactly? 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 Commented Dec 4, 2018 at 9:54
  • Georg wants to know how you read/load the raw content? This is why the complete code snippet will be very useful. Or, at least, tell us how you store bytes (for example, as ArrayBuffer or Blob)? 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é) Commented Dec 4, 2018 at 13:09

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you for the answer
Do you have any example of storing a PDF into a Blob using a remote URL as the source PDF? Not locally neither using select files in HTML.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.