Home  >  Article  >  Web Front-end  >  Detailed introduction to JavaScript using btoa and atob for Base64 transcoding and decoding

Detailed introduction to JavaScript using btoa and atob for Base64 transcoding and decoding

黄舟
黄舟Original
2017-03-21 14:28:171920browse

javascriptThe native api originally supports Base64, but due to the limitations of previous javascript, Base64 is basically useless. When the current HTML5 standard is formalized, Base64 will have a large space for transformation. For Html5 APIs such as FileReader API, drag and drop upload, and even Canvas and Video screenshots,

javascript native APIs can be realized It originally supported Base64, but due to the limitations of previous javascript, Base64 was basically useless. When the current HTML5 standard is formalized, Base64 will have a large space for transformation. For Html5 APIs such as FileReader API, drag and drop upload, and even Canvas and Video screenshots can be implemented.

Okay, the preface has said a lot about the methods of Base64 transcoding and decoding:

1. Let’s take a look at how to use Base64 transcoding in javascript

var str = 'javascript';

window.btoa(str)
//转码结果 "amF2YXNjcmlwdA=="

window.atob("amF2YXNjcmlwdA==")
//解码结果 "javascript"

2. For transcoding, the object of Base64 transcoding can only be string, therefore, for other data There are certain limitations. What needs special attention here is the Unicode transcoding.

var str = "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 method is not possible, so how to make it support Chinese characters?

This requires using window.encodeURIComponent and window.decodeURIComponent

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

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

The above is the detailed content of Detailed introduction to JavaScript using btoa and atob for Base64 transcoding and decoding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn