Base64编码
Base64编码是对二进制数据进行编码,表示成文本格式
图片上传可以分为流上传跟文本上传
这里的文本上传就是指的使用base64的方式 将图片先转换成base64的文本 然后通过字符串接受上传
Base64编码可以把任意长度的二进制数据变为纯文本,且只包含A~Z、a~z、0~9、+、/、=这些字符。
原理
原理是把3字节的二进制数据按6bit一组,用4个int整数表示,然后查表,把int整数用索引对应到字符,得到编码后的字符串

coding
编码
byte[] input = new byte[] { (byte) 0xe4, (byte) 0xb8, (byte) 0xad };
String b64encoded = Base64.getEncoder().encodeToString(input);
System.out.println(b64encoded); // 5Lit
有时候为什么总会有两个==出现在结尾
输入的byte[]数组长度不是3的整数倍 这种情况下,输入的末尾自动补一个或两个0x00,编码后,在结尾加一个=表示补充了1个0x00,加两个=表示补充了2个0x00,解码的时候,去掉末尾补充的一个或两个0x00即可
byte[] input = new byte[] { (byte) 0xe4, (byte) 0xb8, (byte) 0xad, 0x21 };
String b64encoded = Base64.getEncoder().encodeToString(input);
String b64encoded2 = Base64.getEncoder().withoutPadding().encodeToString(input); // 编码的时候不补充 0x00
System.out.println(b64encoded); // 5LitIQ==
System.out.println(b64encoded2); // 5LitIQ
byte[] output = Base64.getDecoder().decode(b64encoded2); // 没有补充0x00也可以解出来
System.out.println(Arrays.toString(output)); // [-28, -72, -83, 33]
有没有那么一种base64加密是针对URL参数的
有
一种针对URL的Base64编码可以在URL中使用的Base64编码,它仅仅是把+变成-,/变成_
Base64.getUrlEncoder().encodeToString(input);
解码
byte[] output = Base64.getDecoder().decode("5Lit");
System.out.println(Arrays.toString(output)); // [-28, -72, -83]
网友评论