and using javascript btoa atob to Base64 decoding and transcoding

and using javascript btoa atob to Base64 decoding and transcoding

javascript native api support already, Base64, but because of the limitations of previous javascript, resulting in Base64 basically useless. The current standard html5 formalize the occasion, Base64 transformation will have a larger space for Html5 Api appear as FileReader Api, drag and drop uploading, and even Canvas, Video screenshots can be achieved.

Well, the preface said a lot of developers need to pay attention to:

A. Let's look at how to use Base64 transcoding in javascript

var str = 'javascript'; window.btoa (str) // transcodes "amF2YXNjcmlwdA ==" window.atob ( "amF2YXNjcmlwdA ==") // decoding result "javascript"

II. For transcoding, the object can only be transcoded Base64 string, so it is, that there are some limitations to other data in this particular note is Unicode transcoding.

var str = "China, China" window.btoa (str)

Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Obviously, this approach does not work, then how does he support Chinese characters, it is necessary to use window.encodeURIComponent and window.decodeURIComponent

var str ="China,中国";window.btoa(window.encodeURIComponent(str))//"Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ="window.decodeURIComponent(window.atob('Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ='))//"China,中国"

Reproduced in: https: //www.jianshu.com/p/aa29e077d139

Guess you like

Origin blog.csdn.net/weixin_34391854/article/details/91226666