使用springboot開發(fā)
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 壓縮字符串 類型為:? 3)°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.后端控制臺輸出: