admin管理员组文章数量:1414621
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);
本文标签: How to base64 encode a raw PDF content (bytes) in JAVASCRIPTStack Overflow
版权声明:本文标题:How to base64 encode a raw PDF content (bytes) in JAVASCRIPT? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745154802a2645104.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论