后端返回前端一般直接用Nginx或者Tomcat就可以自动实现Gzip,但前端发送给后端就需要额外的代码实现,这个就看需求了,如果需要发送大量可压缩率高的文本,可以通过此方法实现压缩字符串,再发送。

源码地址:https://gitee.com/tczmh/GzipDemo
演示地址:https://tczmh.gitee.io/gzipdemo

代码

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>测试Gzip</title>
  6. </head>
  7. <body>
  8. <div>
  9. <span style="font-size: 12px;color: darkgray">内容越长,重复率越高,压缩效果越好,如果字数过少,压缩率可能超过100%</span>
  10. </div>
  11. <textarea id="input" oninput="input()" rows="12" cols="56"></textarea>
  12. <div>
  13. <span>原文:</span>
  14. <span id="yw"></span>
  15. </div>
  16. <div>
  17. <span>压缩:</span>
  18. <span id="ys"></span>
  19. </div>
  20. <div>
  21. <span>解压:</span>
  22. <span id="jy"></span>
  23. </div>
  24. <div>
  25. <span>压缩率:</span>
  26. <span id="ysl"></span>
  27. </div>
  28. <script src="https://cdn.staticfile.org/pako/1.0.10/pako.min.js"></script>
  29. <!--如果需要支持那些不自带atob btoa的浏览器,就需要用下面这个包来进行base64-->
  30. <!--<script src="https://cdn.staticfile.org/Base64/1.0.2/base64.min.js"></script>-->
  31. <script>
  32. function input() {
  33. const input = document.getElementById('input').value;
  34. const ys = zip(input);
  35. const jy = unzip(ys);
  36. document.getElementById('yw').innerText = input;
  37. document.getElementById('ys').innerText = ys;
  38. document.getElementById('jy').innerText = jy;
  39. document.getElementById('ysl').innerText = (Math.round(length(ys) / length(input) * 10000) / 100.00 + "%");
  40. }
  41. // 解压
  42. function unzip(b64Data) {
  43. let strData = atob(b64Data);
  44. const charData = strData.split('').map(function (x) {
  45. return x.charCodeAt(0);
  46. });
  47. const binData = new Uint8Array(charData);
  48. const data = pako.inflate(binData);
  49. strData = String.fromCharCode.apply(null, new Uint16Array(data));
  50. return decodeURIComponent(strData);
  51. }
  52. // 压缩
  53. function zip(str) {
  54. const binaryString = pako.gzip(encodeURIComponent(str), {to: 'string'})
  55. return btoa(binaryString);
  56. }
  57. // 占用字节数计算(UTF-8)
  58. function length(str) {
  59. let total = 0, charCode, i, len;
  60. for (i = 0, len = str.length; i < len; i++) {
  61. charCode = str.charCodeAt(i);
  62. if (charCode <= 0x007f) {
  63. total += 1;
  64. } else if (charCode <= 0x07ff) {
  65. total += 2;
  66. } else if (charCode <= 0xffff) {
  67. total += 3;
  68. } else {
  69. total += 4;
  70. }
  71. }
  72. return total;
  73. }
  74. </script>
  75. </body>
  76. </html>

运行

运行结果以一段json为例

  1. 原文: {"web-app":{"servlet":[{"servlet-name":"cofaxCDS","servlet-class":"org.cofax.cds.CDSServlet","init-param":{"configGlossary:installationAt":"Philadelphia, PA","configGlossary:adminEmail":"ksm@pobox.com","configGlossary:poweredBy":"Cofax","configGlossary:poweredByIcon":"/images/cofax.gif","configGlossary:staticPath":"/content/static","templateProcessorClass":"org.cofax.WysiwygTemplate","templateLoaderClass":"org.cofax.FilesTemplateLoader","templatePath":"templates","templateOverridePath":"","defaultListTemplate":"listTemplate.htm","defaultFileTemplate":"articleTemplate.htm","useJSP":false,"jspListTemplate":"listTemplate.jsp","jspFileTemplate":"articleTemplate.jsp","cachePackageTagsTrack":200,"cachePackageTagsStore":200,"cachePackageTagsRefresh":60,"cacheTemplatesTrack":100,"cacheTemplatesStore":50,"cacheTemplatesRefresh":15,"cachePagesTrack":200,"cachePagesStore":100,"cachePagesRefresh":10,"cachePagesDirtyRead":10,"searchEngineListTemplate":"forSearchEnginesList.htm","searchEngineFileTemplate":"forSearchEngines.htm","searchEngineRobotsDb":"WEB-INF/robots.db","useDataStore":true,"dataStoreClass":"org.cofax.SqlDataStore","redirectionClass":"org.cofax.SqlRedirection","dataStoreName":"cofax","dataStoreDriver":"com.microsoft.jdbc.sqlserver.SQLServerDriver","dataStoreUrl":"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon","dataStoreUser":"sa","dataStorePassword":"dataStoreTestQuery","dataStoreTestQuery":"SET NOCOUNT ON;select test='test';","dataStoreLogFile":"/usr/local/tomcat/logs/datastore.log","dataStoreInitConns":10,"dataStoreMaxConns":100,"dataStoreConnUsageLimit":100,"dataStoreLogLevel":"debug","maxUrlLength":500}},{"servlet-name":"cofaxEmail","servlet-class":"org.cofax.cds.EmailServlet","init-param":{"mailHost":"mail1","mailHostOverride":"mail2"}},{"servlet-name":"cofaxAdmin","servlet-class":"org.cofax.cds.AdminServlet"},{"servlet-name":"fileServlet","servlet-class":"org.cofax.cds.FileServlet"},{"servlet-name":"cofaxTools","servlet-class":"org.cofax.cms.CofaxToolsServlet","init-param":{"templatePath":"toolstemplates/","log":1,"logLocation":"/usr/local/tomcat/logs/CofaxTools.log","logMaxSize":"","dataLog":1,"dataLogLocation":"/usr/local/tomcat/logs/dataLog.log","dataLogMaxSize":"","removePageCache":"/content/admin/remove?cache=pages&id=","removeTemplateCache":"/content/admin/remove?cache=templates&id=","fileTransferFolder":"/usr/local/tomcat/webapps/content/fileTransferFolder","lookInContext":1,"adminGroupID":4,"betaServer":true}}],"servlet-mapping":{"cofaxCDS":"/","cofaxEmail":"/cofaxutil/aemail/*","cofaxAdmin":"/admin/*","fileServlet":"/static/*","cofaxTools":"/tools/*"},"taglib":{"taglib-uri":"cofax.tld","taglib-location":"/WEB-INF/tlds/cofax.tld"}}}
  2. 压缩: H4sIAAAAAAAAA51XYW/aPBD+NWjSJCIKZf0MSbMxZcAaqn02iRO8OnFmG1reX/+e48SxCbTZpEo1d89zdz777pzRw3I0nb7i/RhVFaxGs8WoFgnMTxTLRjRfOtJxiQrcqKbThGXozQ9iJZj6FiqhSAgDYzz3aqiXpMIDfNy5qGmkJHJcIY4KO5CElRnJv1ImBOJnEJNSSEQpkoSVC2nMbw+EohTT6kBQbW+yXRjTPSMoLUj5WCBCjYEXUYzuJxXbM4iQFbe5FXvFHKfLs6H6alsDCCtQGdJoGpIC5RgyFOq85CS7bQQ2LUmyRfJgWwCYxCVkIdR6w5e4q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3qCXjIyduH/AkTY2HBkSv3PvuJQSE7ouoYes8PwT/A+Z9wE2uDgAA
  3. 解压: {"web-app":{"servlet":[{"servlet-name":"cofaxCDS","servlet-class":"org.cofax.cds.CDSServlet","init-param":{"configGlossary:installationAt":"Philadelphia, PA","configGlossary:adminEmail":"ksm@pobox.com","configGlossary:poweredBy":"Cofax","configGlossary:poweredByIcon":"/images/cofax.gif","configGlossary:staticPath":"/content/static","templateProcessorClass":"org.cofax.WysiwygTemplate","templateLoaderClass":"org.cofax.FilesTemplateLoader","templatePath":"templates","templateOverridePath":"","defaultListTemplate":"listTemplate.htm","defaultFileTemplate":"articleTemplate.htm","useJSP":false,"jspListTemplate":"listTemplate.jsp","jspFileTemplate":"articleTemplate.jsp","cachePackageTagsTrack":200,"cachePackageTagsStore":200,"cachePackageTagsRefresh":60,"cacheTemplatesTrack":100,"cacheTemplatesStore":50,"cacheTemplatesRefresh":15,"cachePagesTrack":200,"cachePagesStore":100,"cachePagesRefresh":10,"cachePagesDirtyRead":10,"searchEngineListTemplate":"forSearchEnginesList.htm","searchEngineFileTemplate":"forSearchEngines.htm","searchEngineRobotsDb":"WEB-INF/robots.db","useDataStore":true,"dataStoreClass":"org.cofax.SqlDataStore","redirectionClass":"org.cofax.SqlRedirection","dataStoreName":"cofax","dataStoreDriver":"com.microsoft.jdbc.sqlserver.SQLServerDriver","dataStoreUrl":"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon","dataStoreUser":"sa","dataStorePassword":"dataStoreTestQuery","dataStoreTestQuery":"SET NOCOUNT ON;select test='test';","dataStoreLogFile":"/usr/local/tomcat/logs/datastore.log","dataStoreInitConns":10,"dataStoreMaxConns":100,"dataStoreConnUsageLimit":100,"dataStoreLogLevel":"debug","maxUrlLength":500}},{"servlet-name":"cofaxEmail","servlet-class":"org.cofax.cds.EmailServlet","init-param":{"mailHost":"mail1","mailHostOverride":"mail2"}},{"servlet-name":"cofaxAdmin","servlet-class":"org.cofax.cds.AdminServlet"},{"servlet-name":"fileServlet","servlet-class":"org.cofax.cds.FileServlet"},{"servlet-name":"cofaxTools","servlet-class":"org.cofax.cms.CofaxToolsServlet","init-param":{"templatePath":"toolstemplates/","log":1,"logLocation":"/usr/local/tomcat/logs/CofaxTools.log","logMaxSize":"","dataLog":1,"dataLogLocation":"/usr/local/tomcat/logs/dataLog.log","dataLogMaxSize":"","removePageCache":"/content/admin/remove?cache=pages&id=","removeTemplateCache":"/content/admin/remove?cache=templates&id=","fileTransferFolder":"/usr/local/tomcat/webapps/content/fileTransferFolder","lookInContext":1,"adminGroupID":4,"betaServer":true}}],"servlet-mapping":{"cofaxCDS":"/","cofaxEmail":"/cofaxutil/aemail/*","cofaxAdmin":"/admin/*","fileServlet":"/static/*","cofaxTools":"/tools/*"},"taglib":{"taglib-uri":"cofax.tld","taglib-location":"/WEB-INF/tlds/cofax.tld"}}}
  4. 压缩率: 53.28%

总结

当文本达到一定长度,且内容中重复的字符出现次数较多,就可以有一个不错的压缩率。通过js实现压缩,发送到后端再实现解压。有效提升同等网络带宽下的传输速率。