Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-03-21 14:28:17
Original
1928 people have browsed it

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"
Copy after login

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)
Copy after login

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,中国"
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!