网站平台怎么做的好处,淘宝自己建的网站,wordpress 添加广告,建设个人网站第一步这么做目录 1.什么是base64
2.在java中使用base64
3.在js中使用base64 1.什么是base64
base64编码就是将字符串以每3个比特#xff08;bit#xff09;的字节子序列拆分为4个6比特#xff08;bit#xff09;的字节子序列#xff08;这个6比特是有效字节#xff0c;最左边两个…目录 1.什么是base64
2.在java中使用base64
3.在js中使用base64 1.什么是base64
base64编码就是将字符串以每3个比特bit的字节子序列拆分为4个6比特bit的字节子序列这个6比特是有效字节最左边两个永远为0其实也算是8比特的字节再将得到的子序列查找base64的编码索引表得到对应的字符拼接成新的字符串的一种编码方式。
2.在java中使用base64
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;public class Base64Util {/**** BASE64解密* param key* return* throws Exception*/public static byte[] decryBASE64(String key) throws Exception {return (new BASE64Decoder()).decodeBuffer(key);}/**** BASE64加密* param key* return* throws Exception*/public static String encryptBASE64(byte[] key) {return (new BASE64Encoder()).encode(key);}/*** 文件的base64加密解密* param filePath* return*/public static void BASE64File(String filePath){try {// 读取文件内容Path path Paths.get(filePath);byte[] fileContent Files.readAllBytes(path);// Base64编码String encodedString Base64.getEncoder().encodeToString(fileContent);System.out.println(Base64编码结果);System.out.println(encodedString);// Base64解码byte[] decodedBytes Base64.getDecoder().decode(encodedString);System.out.println(Base64解码结果);String decodedString new String(decodedBytes);System.out.println(decodedString);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) throws Exception {String base64 encryptBASE64(hello world.getBytes(StandardCharsets.UTF_8));System.out.println(base64编码后:base64);System.out.println(base64解码:new String(decryBASE64(base64)));BASE64File(C:\\Users\\Administrator\\Desktop\\helloworld.txt);//本地文件路径}}结果如下 使用的文件如下 3.在js中使用base64
// Base64编码
var originalString Hello, World!;
var encodedString btoa(originalString);
console.log(Base64编码结果, encodedString);// Base64解码
var decodedString atob(encodedString);
console.log(Base64解码结果, decodedString);
具体的案例可参考如下如果您需要在浏览器环境中处理文件的Base64编码可以使用FileReader来读取文件内容并使用btoa()函数将内容转换为Base64编码字符串。以下是一个简单的示例代码演示了如何在浏览器环境中将文件内容进行Base64编码
// 选择文件并读取内容
var input document.createElement(input);
input.type file;
input.onchange function(e) {var file e.target.files[0];var reader new FileReader();reader.onload function(e) {var fileContent e.target.result;var base64String btoa(fileContent);console.log(文件的Base64编码结果, base64String);};reader.readAsBinaryString(file);
};
input.click();