美文网首页
java压缩字符串,前端接收pako解压

java压缩字符串,前端接收pako解压

作者: 江上流 | 来源:发表于2019-10-31 13:34 被阅读0次

使用springboot开发

1.后端java代码压缩:

```

/**

* 测试GZIP压缩之后返回给前端,前端使用pako解压缩

* @return

* @throws IOException

*/

@PostMapping(value ="/pakoGzipTest")

public String pakoGzipTest()throws IOException {

// 字符串超过一定的长度

    StringBuilder sb =new StringBuilder();

sb.append("<section style=\"box-sizing: border-box; text-align: justify;\"><section style=\"position: static; box-sizing: border-box;\" powered-by=\"xiumi.us\">");

sb.append("<section style=\"text-align: center; margin: -10px 0% 10px; position: static; box-sizing: border-box;\"><section style=\"max-width: 100%; vertical-align: middle; display: ");

sb.append("inline-block; line-height: 0; width: 95%; box-sizing: border-box;\">");

sb.append("测试Java的GZIP压缩字符串,在前端js中使用pako解压还原</span></p>");

String str=sb.toString();

System.out.println("原始字符串长度:"+str.length());

String zip = PakoGzipUtils.compress(str);

System.out.println("压缩之后的字符串前100:"+zip.substring(0,100));

System.out.println("压缩编码后字符串长度:"+zip.length());

System.out.println("压缩比:"+(float)zip.length()/(float)str.length());

return zip;

}

```

2.后端java使用的压缩公共类PakoGzipUtils:

public class PakoGzipUtils {

/**

    * @param str:正常的字符串

    * @return 压缩字符串 类型为:  ³)°K,NIc i£_`Çe#  c¦%ÂXHòjyIÅÖ`

    * @throws IOException

*/

    public static String compress(String str)throws IOException {

if (str ==null || str.length() ==0) {

return str;

}

ByteArrayOutputStream out =new ByteArrayOutputStream();

GZIPOutputStream gzip =new GZIPOutputStream(out);

gzip.write(str.getBytes());

gzip.close();

return out.toString("ISO-8859-1");

}

}

3.前端页面(只是简单的一个html测试页面):

```

<html>

<body>

<input type="button" value="测试pako解压java传过来的压缩字符串" onclick="pakoTest();" />

<div>#####################我是分割线#######################</div>

<div id="d2"></div>

</body>

<script src="/js/jquery.min.js" charset="utf-8"></script>

<script src="/js/pako.min.js" charset="utf-8"></script>

<script>

function pakoTest() {

alert(1);

$.ajax({

url:'http://localhost:9000/pakoGzipTest',

type:"POST",

success:function(rtn){

$('#d2').text(pako_ungzip(rtn));

},

error:function (rtn) {

alert("失败了");

}

});

alert(2);

}

//解压字符串

    function pako_ungzip(str){

try{

var restored =pako.ungzip( str, {to:'string' } );

}catch(err){

console.log("异常:"+err);

}

return restored;

}

</script>

</html>

```

4.前端浏览器展示:

5.后端控制台输出:

相关文章

网友评论

      本文标题:java压缩字符串,前端接收pako解压

      本文链接:https://www.haomeiwen.com/subject/otadyctx.html