简体   繁体   中英

How to base64 encode a raw PDF content (bytes) in JAVASCRIPT?

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 !

[ 在此处输入图片说明

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);

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