java后端与js前端pako压缩与解压的使用(加快前后端传输速度)

1,js引入pako解压后端传过来的数据
//js解压缩
import pako from 'pako';   //npm安装pako后引入进来

 //解压 ,传入后端压缩的数据
    uncompress(strData) {
      let charData = strData.split("").map(function (x) {
        return x.charCodeAt(0);
      });  //按字符分割成数组
      let binData = new Uint8Array(charData);   //数组转换为Uint8Array类型
      let data = pako.inflate(binData);    //数组转换为Uint8Array类型
      let utf8ArrayToStr = Utf8ArrayToStr(data);  // Uint8Array类型转为字符串
      let responseDataStr = JSON.parse(utf8ArrayToStr);   //Json字符串转为对象
      return responseDataStr;

      //解决数据过大和中文乱码
      function Utf8ArrayToStr(array) {
        let out, i, len, c;
        let char2, char3;

        out = "";
        len = array.length;
        i = 0;
        while (i < len) {
          c = array[i++];
          switch (c >> 4) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
              // 0xxxxxxx
              out += String.fromCharCode(c);
              break;
            case 12:
            case 13:
              // 110x xxxx   10xx xxxx
              char2 = array[i++];
              out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
              break;
            case 14:
              // 1110 xxxx  10xx xxxx  10xx xxxx
              char2 = array[i++];
              char3 = array[i++];
              out += String.fromCharCode(((c & 0x0F) << 12) |
                  ((char2 & 0x3F) << 6) |
                  ((char3 & 0x3F) << 0));
              break;
          }
        }
        return out;
      }
    },

2,创建后端java压缩类

//java后端压缩  

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {
    /**
     * 字符串的压缩
     *
     * @param str  待压缩的字符串
     * @return    返回压缩后的字符串
     */
    public static String compress(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return null;
        }
        // 创建一个新的 byte 数组输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用默认缓冲区大小创建新的输出流
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes("UTF-8"));
        gzip.close();
        // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
        return out.toString("ISO-8859-1");
    }

}

3,后端使用,把需要压缩的对象先变为json字符串
           ObjectMapper objectToStr = new ObjectMapper(); 
           String jsonString = objectToStr.writeValueAsString(customerObject); //把对象变为json字符串
            String compress = GzipUtil.compress(jsonString);  //压缩数据 ,前端接收要解压

你可能感兴趣的:(前端,java,javascript)