javascript uses btoa and atob to transcode and decode Base64

  • 2021-08-05 08:29:51
  • OfStack

The native api of javascript originally supports Base64, but due to the limitations of the previous javascript, Base64 is basically useless. At present, when the html5 standard is formalized, Base64 will have a large transformation space, which can be realized for Html5 Api, such as FileReader Api, drag and upload, and even screenshots of Canvas and Video.

Ok, the preface says a lot. What are the methods of Base64 transcoding and decoding:

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


var str = 'javascript';

window.btoa(str)
// Transcoding result  "amF2YXNjcmlwdA=="

window.atob("amF2YXNjcmlwdA==")
// Decoding result  "javascript"

2. For transcoding, the object transcoded by Base64 can only be a string, so there are some limitations for other data, and special attention should be paid to transcoding Unicode.


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 way can't work, so how can he support Chinese characters?

This uses window. encodeURIComponent and window. decodeURIComponent


var str = "China China ";
window.btoa(window.encodeURIComponent(str))
//"Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ="

window.decodeURIComponent(window.atob('Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ='))
//"China China "

Related articles: