JS Implementation of the Chinese string UTF-8 Base64 encoding method (make it the same as Java coding), utf-8base64

Source: Internet
Author: User

JS Implementation of the Chinese string UTF-8 Base64 encoding method (make it the same as Java coding), utf-8base64

This example describes how to use JavaScript to encode Chinese strings with UTF-8 in base64. We will share this with you for your reference. The details are as follows:

String to be encoded: "select User name from user"

Use JAVA for encoding. Java program:

String SQL = "select username from user"; String encodeStr = new String (Base64.encode (SQL. getBytes ("UTF-8"); // encode System. out. println (encodeStr );

Get:

c2VsZWN0IOeUqOaIt+WQjSBmcm9tIOeUqOaItw==

Decoding in Java:

sql = new String(Base64.decode(sql.getBytes()), "UTF-8");

Why use getBytes ("UTF-8") in Java code? Because the default encoding is different in Windows and Linux environments, you must specify the encoding to make your program get the same encoding on different platforms.

Although Html and JS encoding are UTF-8, but JS from the page to get the Chinese encoding is UTF-16, so the direct Chinese Base64 encoding will get the wrong result, so we need to first convert from the UTF-16 to UTF-8 and then encode

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

The above code is obtained from the Internet and the correct result is obtained after splicing. Thanks to our predecessors.

PS: here we recommend several online base64 encoding and decoding tools. I believe they will be used in future development:

BASE64 encoding and decoding tool:
Http://tools.jb51.net/transcoding/base64

Online image conversion BASE64 tool:
Http://tools.jb51.net/transcoding/img2base64

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.