Java Gzip类 - base64压缩和解压
public final class ZipUtil
{
public static String CompressToBase64(String string){
try {
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
String result = Base64.encodeToString(compressed, Base64.DEFAULT);
return result;
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception ex){
}
return "";
}
public static String DecompressToBase64(String textToDecode){
//String textToDecode = "H4sIAAAAAAAAAPNIzcnJBwCCidH3BQAAAA==\n";
try {
byte[] compressed = Base64.decode(textToDecode, Base64.DEFAULT);
final int BUFFER_SIZE = 32;
ByteArrayInputStream inputStream = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(inputStream, BUFFER_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) {
baos.write(data, 0, bytesRead);
}
return baos.toString("UTF-8");
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception ex){
}
return "";
}
}
前端:
下载与引入pako
下载:npm install pako
引入:import pako from "pako"
function arrayBufferToString(buffer){
var bufView = new Uint16Array(buffer);
var length = bufView.length;
var result = '';
var addition = Math.pow(2,16)-1;
for(var i = 0;i<length;i+=addition){
if(i + addition > length){
addition = length - i;
}
result += String.fromCharCode.apply(null, bufView.subarray(i,i+addition));
}
return result;
}
// b64Data-->传入加密的数据进行解密
function unzip (b64Data) {
let strData = atob(b64Data)
// 将二进制字符串转换为字符数数组
const charData = strData.split('').map(function (x) { return x.charCodeAt(0) })
// 将数字数组转换为字节数组
const binData = new Uint8Array(charData)
// // unzip
const data = pako.inflate(binData)
// 将gunzipped byteArray转换回ascii字符串:
strData = arrayBufferToString(new Uint16Array(data))
return decodeURIComponent(escape(strData))
}
// 加密
function zip (str) {
if (typeof str !== 'string') {
str = JSON.stringify(str)
}
const binaryString = pako.gzip(str, { to: 'string' })
return btoa(binaryString)
}
export {
unzip,
zip
}
在页面中导入
import { unzip } from '@/utils/pako'
使用:
this.data = JSON.parse(unzip(res.message))