申明,全篇内容都是基于pako.js来实现gzip压缩字符串,本文只是介绍简单用法

前言

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

在线演示DEMO地址:
https://tczmh.gitee.io/gzipdemo/

GITEE源码地址:
https://gitee.com/tczmh/GzipDemo

代码

<!DOCTYPE html><html lang="zh-CN"><head>
    <meta charset="UTF-8">
    <title>测试Gzip</title></head><body><div>
    <span style="font-size: 12px;color: darkgray">内容越长,重复率越高,压缩效果越好,如果字数过少,压缩率可能超过100%</span></div><textarea id="input" oninput="input()" rows="12" cols="56"></textarea><div>
    <span>原文:</span>
    <span id="yw"></span></div><div>
    <span>压缩:</span>
    <span id="ys"></span></div><div>
    <span>解压:</span>
    <span id="jy"></span></div><div>
    <span>压缩率:</span>
    <span id="ysl"></span></div><script src="https://cdn.staticfile.org/pako/1.0.10/pako.min.js"></script><!--如果需要支持那些不自带atob btoa的浏览器,就需要用下面这个包来进行base64--><!--<script src="https://cdn.staticfile.org/Base64/1.0.2/base64.min.js"></script>--><script>
    function input() {
        const input = document.getElementById('input').value;
        const ys = zip(input);
        const jy = unzip(ys);
        document.getElementById('yw').innerText = input;
        document.getElementById('ys').innerText = ys;
        document.getElementById('jy').innerText = jy;
        document.getElementById('ysl').innerText = (Math.round(length(ys) / length(input) * 10000) / 100.00 + "%");

    }

    // 解压
    function unzip(b64Data) {
        let strData = atob(b64Data);
        const charData = strData.split('').map(function (x) {
            return x.charCodeAt(0);
        });
        const binData = new Uint8Array(charData);
        const data = pako.inflate(binData);
        strData = String.fromCharCode.apply(null, new Uint16Array(data));
        return decodeURIComponent(strData);
    }

    // 压缩
    function zip(str) {
        const binaryString = pako.gzip(encodeURIComponent(str), {to: 'string'})
        return btoa(binaryString);
    }

    // 占用字节数计算(UTF-8)
    function length(str) {
        let total = 0, charCode, i, len;
        for (i = 0, len = str.length; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode <= 0x007f) {
                total += 1;
            } else if (charCode <= 0x07ff) {
                total += 2;
            } else if (charCode <= 0xffff) {
                total += 3;
            } else {
                total += 4;
            }
        }
        return total;
    }</script></body></html>

运行

运行结果以一段json为例

原文: {"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"}}}
压缩: H4sIAAAAAAAAA51XYW/aPBD+NWjSJCIKZf0MSbMxZcAaqn02iRO8OnFmG1reX/+e48SxCbTZpEo1d89zdz777pzRw3I0nb7i/RhVFaxGs8WoFgnMTxTLRjRfOtJxiQrcqKbThGXozQ9iJZj6FiqhSAgDYzz3aqiXpMIDfNy5qGmkJHJcIY4KO5CElRnJv1ImBOJnEJNSSEQpkoSVC2nMbw+EohTT6kBQbW+yXRjTPSMoLUj5WCBCjYEXUYzuJxXbM4iQFbe5FXvFHKfLs6H6alsDCCtQGdJoGpIC5RgyFOq85CS7bQQ2LUmyRfJgWwCYxCVkIdR6w5e4qCBHeMtZgoVg3L9xGL/Ogrye812D7xmIGGT1JjskFIudA+2HYMfcCkUPtjlhzkmKL7bYoFKcoSOVERHSDrUGUUvoHWRxSVJB9kiIQ7o6ucM7Cvw93mpohqjAWvxbVB/7B5CxA+tBvm1OgpID5CB5gauxQ7nYcVhr5nQyuY6JJeP4A8wTzjgWTWa/2KA2DNvV3eQqwnI0vwpwvNzNnVBy/N5mcsf6XV/rmu6pA8Ll+Qmj1AUIjHhyeCxzUuKrh5cxHlsYoUDOZbAtXD3NSws32U/QW6QI9ob563E5Xq1DqF5eq7x0b9/BAElk5UTyY3MR01ZxqyzjP9Qh1yxoQYTjRPXNd3hPHaqro9bWutf3+5iAk5PuAg2q8AqScCZYJr3f6T7xxB+qRgTmXvwziutVR3KNPfOuQSsurIwx1RRbSzVCJTLa+Ivo2ybeqTtwP5uNZkuViT0SOvhZkLNrO3sWVswC9QFbyNgr46kBGc0OC/nziPm5T3JUNSt+3MFoWm/8zfNarTZriFBgChmHX1BBsK3gk/r/CRR9ixHL1SW0Z8BRQOQhZQmCXIWSFQmStSBXo0UxhWJ6IOjbW8HQ9VlZCrdsjP4HjHZbfalXymcBBRiRgshbKIg6wifcnWWK98cumgK9wUFHuMzb1j8HEw+B+gPAB08PM8YHPz5qxrDnh0J+Y6J7ZyjBnRW5VrfDy4HV02voLhbqRfJXu6gZ1i4+cpPBvbnc9BA/ocsbtJsdY1QM91LAg9DQhh3M9deF4ltPjNAYaS4/XE7zO4KKadvcsFrqYnSKCdZQJjH5zy5Lq9CiC9+N7O/9N8ReJUfvBMBxwU71iPTVrLSddY9HpC9fqMGjWVjPVehElX6gfiEp/Liw2Q7Cf7FrndGFbXVL4ZlQigzzkNHUasu38wMfMPD9Ihzf1w01B8ZeVqWvoG/SOZo64K+cHatVoBX3WrHH0Mr0qOmGsa7teeDe8gJCIWVuX1b7E6ndionGbWJdEkF6lEoYIqy14WeXZHpGS2rz/dlJZ+x8y9XA9mvh0qKp2xYotUDjHpqdSpRTsrc3qCXjIyduH/AkTY2HBkSv3PvuJQSE7ouoYes8PwT/A+Z9wE2uDgAA
解压: {"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"}}}
压缩率: 53.28%

总结

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

转自:https://www.jianshu.com/p/5cbaaeb52dbb