博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript中base64和Gzip的使用
阅读量:6876 次
发布时间:2019-06-26

本文共 13967 字,大约阅读时间需要 46 分钟。

一般的使用流程(4步):

服务器端将字符串Gzip压缩为 字节数组——>通过base64转为字符串(后传递到客户端)——>解码base64字符串为字节数组——>Gzip解码字节数组为可用字符串。

第一步:服务器端压缩(本人使用的是C#)

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.Serialization.Json;using System.Text;using System.Web;using ICSharpCode.SharpZipLib.BZip2;using ICSharpCode.SharpZipLib.GZip;using ICSharpCode.SharpZipLib.Zip;namespace amtioth5.Helper{    public enum CompressionType    {        ///         /// GZip 压缩格式        ///         GZip,        ///         /// BZip2 压缩格式        ///         BZip2,        ///         /// Zip 压缩格式        ///         Zip    }    public class CompressHelper    {        public static CompressionType CompressionProvider = CompressionType.GZip;        #region Public methods        ///         /// 从原始字节数组生成已压缩的字节数组。        ///         /// 原始字节数组。        /// 
返回已压缩的字节数组
public static byte[] Compress(byte[] bytesToCompress) { MemoryStream ms = new MemoryStream(); Stream s = OutputStream(ms); s.Write(bytesToCompress, 0, bytesToCompress.Length); s.Close(); return ms.ToArray(); } /// /// 从原始字符串生成已压缩的字符串。 /// /// 原始字符串。 ///
返回已压缩的字符串。
public static string Compress(string stringToCompress) { byte[] compressedData = CompressToByte(stringToCompress); string strOut = Convert.ToBase64String(compressedData); return strOut; } /// /// 从原始字符串生成已压缩的字节数组。 /// /// 原始字符串。 ///
返回已压缩的字节数组。
public static byte[] CompressToByte(string stringToCompress) { byte[] bytData = Encoding.UTF8.GetBytes(stringToCompress); return Compress(bytData); } /// /// 从已压缩的字符串生成原始字符串。 /// /// 已压缩的字符串。 ///
返回原始字符串。
public static string DeCompress(string stringToDecompress) { string outString = string.Empty; if (stringToDecompress == null) { throw new ArgumentNullException("stringToDecompress", "You tried to use an empty string"); } try { byte[] inArr = Convert.FromBase64String(stringToDecompress.Trim()); byte[] deArr = DeCompress(inArr); outString = Encoding.UTF8.GetString(deArr, 0, deArr.Length); } catch (NullReferenceException nEx) { return nEx.Message; } return outString; } /// /// 从已压缩的字节数组生成原始字节数组。 /// /// 已压缩的字节数组。 ///
返回原始字节数组。
public static byte[] DeCompress(byte[] bytesToDecompress) { byte[] writeData = new byte[4096]; Stream s2 = InputStream(new MemoryStream(bytesToDecompress)); MemoryStream outStream = new MemoryStream(); while (true) { int size = s2.Read(writeData, 0, writeData.Length); if (size > 0) { outStream.Write(writeData, 0, size); } else { break; } } s2.Close(); byte[] outArr = outStream.ToArray(); outStream.Close(); return outArr; } #endregion #region Private methods /// /// 从给定的流生成压缩输出流。 /// /// 原始流。 ///
返回压缩输出流。
private static Stream OutputStream(Stream inputStream) { switch (CompressionProvider) { case CompressionType.BZip2: return new BZip2OutputStream(inputStream); case CompressionType.GZip: return new GZipOutputStream(inputStream); case CompressionType.Zip: return new ZipOutputStream(inputStream); default: return new GZipOutputStream(inputStream); } } /// /// 从给定的流生成压缩输入流。 /// /// 原始流。 ///
返回压缩输入流。
private static Stream InputStream(Stream inputStream) { switch (CompressionProvider) { case CompressionType.BZip2: return new BZip2InputStream(inputStream); case CompressionType.GZip: return new GZipInputStream(inputStream); case CompressionType.Zip: return new ZipInputStream(inputStream); default: return new GZipInputStream(inputStream); } } #endregion public static T FromJsonTo
(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T jsonObject = (T)ser.ReadObject(ms); ms.Close(); return jsonObject; } public static string ToJsonString(object item) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, item); StringBuilder sb = new StringBuilder(); byte[] bytes = ms.ToArray(); sb.Append(Encoding.UTF8.GetString(bytes, 0, bytes.Length)); return sb.ToString(); } } }}
View Code

http://icsharpcode.github.io/SharpZipLib/  (需要一个依赖库是开源的)

第二步:使用base64将压缩后的字节变为base64字符串 (Convert.ToBase64String();)

此转换为.net平台里面自带的函数。

第三部:客户端在Javascript中利用zip.js将base64字符串解码为压缩字节

var bytes = Base64.decodeToBytes(base_ut8);///important

上面代码将base_ut8变量中的字符串转为字节数组。

第四部:解压第三步得到的字节数组

// compressed = Array.
or Uint8Arrayvar gunzip = new Zlib.Gunzip(compressed);var plain = gunzip.decompress();

下面我写的一个流程

document.write("");document.write("");document.write("");document.write("");var GzipHelper={    DeCompressGzip:function(base64str){        if(base64str===null||base64str==='') return '';        var bytes =  Base64.decodeToBytes(base64str);        var  gunzip  =  new  Zlib.Gunzip ( bytes );        var plain = gunzip.decompress();        var asciistring = new TextDecoder("utf-8").decode(plain);        return asciistring;            },    CompressGzip:function(jsonstr){            }}
View Code

 相关文件下载链接: http://pan.baidu.com/s/1jING8Hw 密码: erap

base64的转码和解码

/*** UTF16和UTF8转换对照表* U+00000000 – U+0000007F   0xxxxxxx* U+00000080 – U+000007FF   110xxxxx 10xxxxxx* U+00000800 – U+0000FFFF   1110xxxx 10xxxxxx 10xxxxxx* U+00010000 – U+001FFFFF   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx* U+00200000 – U+03FFFFFF   111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx* U+04000000 – U+7FFFFFFF   1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx*/var Base64 = {    // 转码表    table : [            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',            'I', 'J', 'K', 'L', 'M', 'N', 'O' ,'P',            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',            'w', 'x', 'y', 'z', '0', '1', '2', '3',            '4', '5', '6', '7', '8', '9', '+', '/',        '='    ],    UTF16ToUTF8 : function(str) {        var res = [], len = str.length;        for (var i = 0; i < len; i++) {            var code = str.charCodeAt(i);            if (code > 0x0000 && code <= 0x007F) {                // 单字节,这里并不考虑0x0000,因为它是空字节                // U+00000000 – U+0000007F  0xxxxxxx                res.push(str.charAt(i));            } else if (code >= 0x0080 && code <= 0x07FF) {                // 双字节                // U+00000080 – U+000007FF  110xxxxx 10xxxxxx                // 110xxxxx                var byte1 = 0xC0 | ((code >> 6) & 0x1F);                // 10xxxxxx                var byte2 = 0x80 | (code & 0x3F);                res.push(                    String.fromCharCode(byte1),                     String.fromCharCode(byte2)                );            } else if (code >= 0x0800 && code <= 0xFFFF) {                // 三字节                // U+00000800 – U+0000FFFF  1110xxxx 10xxxxxx 10xxxxxx                // 1110xxxx                var byte1 = 0xE0 | ((code >> 12) & 0x0F);                // 10xxxxxx                var byte2 = 0x80 | ((code >> 6) & 0x3F);                // 10xxxxxx                var byte3 = 0x80 | (code & 0x3F);                res.push(                    String.fromCharCode(byte1),                     String.fromCharCode(byte2),                     String.fromCharCode(byte3)                );            } else if (code >= 0x00010000 && code <= 0x001FFFFF) {                // 四字节                // U+00010000 – U+001FFFFF  11110xxx 10xxxxxx 10xxxxxx 10xxxxxx            } else if (code >= 0x00200000 && code <= 0x03FFFFFF) {                // 五字节                // U+00200000 – U+03FFFFFF  111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx            } else /** if (code >= 0x04000000 && code <= 0x7FFFFFFF)*/ {                // 六字节                // U+04000000 – U+7FFFFFFF  1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx            }        }         return res.join('');    },    UTF8ToUTF16 : function(str) {        var res = [], len = str.length;        var i = 0;        for (var i = 0; i < len; i++) {            var code = str.charCodeAt(i);            // 对第一个字节进行判断            if (((code >> 7) & 0xFF) == 0x0) {                // 单字节                // 0xxxxxxx                res.push(str.charAt(i));            } else if (((code >> 5) & 0xFF) == 0x6) {                // 双字节                // 110xxxxx 10xxxxxx                var code2 = str.charCodeAt(++i);                var byte1 = (code & 0x1F) << 6;                var byte2 = code2 & 0x3F;                var utf16 = byte1 | byte2;                res.push(Sting.fromCharCode(utf16));            } else if (((code >> 4) & 0xFF) == 0xE) {                // 三字节                // 1110xxxx 10xxxxxx 10xxxxxx                var code2 = str.charCodeAt(++i);                var code3 = str.charCodeAt(++i);                var byte1 = (code << 4) | ((code2 >> 2) & 0x0F);                var byte2 = ((code2 & 0x03) << 6) | (code3 & 0x3F);                var utf16 = ((byte1 & 0x00FF) << 8) | byte2                res.push(String.fromCharCode(utf16));            } else if (((code >> 3) & 0xFF) == 0x1E) {                // 四字节                // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx            } else if (((code >> 2) & 0xFF) == 0x3E) {                // 五字节                // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx            } else /** if (((code >> 1) & 0xFF) == 0x7E)*/ {                // 六字节                // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx            }        }         return res.join('');    },    encode : function(str) {        if (!str) {            return '';        }        var utf8    = this.UTF16ToUTF8(str); // 转成UTF8        var i = 0; // 遍历索引        var len = utf8.length;        var res = [];        while (i < len) {            var c1 = utf8.charCodeAt(i++) & 0xFF;            res.push(this.table[c1 >> 2]);            // 需要补2个=            if (i == len) {                res.push(this.table[(c1 & 0x3) << 4]);                res.push('==');                break;            }            var c2 = utf8.charCodeAt(i++);            // 需要补1个=            if (i == len) {                res.push(this.table[((c1 & 0x3) << 4) | ((c2 >> 4) & 0x0F)]);                res.push(this.table[(c2 & 0x0F) << 2]);                res.push('=');                break;            }            var c3 = utf8.charCodeAt(i++);            res.push(this.table[((c1 & 0x3) << 4) | ((c2 >> 4) & 0x0F)]);            res.push(this.table[((c2 & 0x0F) << 2) | ((c3 & 0xC0) >> 6)]);            res.push(this.table[c3 & 0x3F]);        }         return res.join('');    },    decode : function(str) {        if (!str) {            return '';        }         var len = str.length;        var i   = 0;        var res = [];         while (i < len) {            code1 = this.table.indexOf(str.charAt(i++));            code2 = this.table.indexOf(str.charAt(i++));            code3 = this.table.indexOf(str.charAt(i++));            code4 = this.table.indexOf(str.charAt(i++));             c1 = (code1 << 2) | (code2 >> 4);            c2 = ((code2 & 0xF) << 4) | (code3 >> 2);            c3 = ((code3 & 0x3) << 6) | code4;             res.push(String.fromCharCode(c1));             if (code3 != 64) {                res.push(String.fromCharCode(c2));            }            if (code4 != 64) {                res.push(String.fromCharCode(c3));            }         }         return this.UTF8ToUTF16(res.join(''));    },    decodeToBytes : function(str) {        if (!str) {            return '';        }         var len = str.length;        var i   = 0;        var res = [];         while (i < len) {            code1 = this.table.indexOf(str.charAt(i++));            code2 = this.table.indexOf(str.charAt(i++));            code3 = this.table.indexOf(str.charAt(i++));            code4 = this.table.indexOf(str.charAt(i++));             c1 = (code1 << 2) | (code2 >> 4);            c2 = ((code2 & 0xF) << 4) | (code3 >> 2);            c3 = ((code3 & 0x3) << 6) | code4;             res.push(c1);            if (code2 != 64) {                res.push(c2);            }            if (code3 != 64) {                res.push(c3);            }                             }        res.pop();         return res;    }};
View Code

Gzip的转码和解码(zlib.js库)

https://github.com/imaya/zlib.js/blob/master/README.en.md

附带一个编码转换库(text-encoding)

https://github.com/inexorabletash/text-encoding

转载于:https://www.cnblogs.com/lwngreat/p/5369703.html

你可能感兴趣的文章
我的友情链接
查看>>
Exchange Server 运维管理01:Exchange中Active Directory 有什么用?
查看>>
linux系统管理之四:服务状态
查看>>
VMware View FAQ[一]
查看>>
【原创翻译】布尔值(boolean)
查看>>
三元运算式、lambda表达式、内置函数map、reduce、filter以及yield生成器
查看>>
MySQL分库分表分表后数据的查询(5th)
查看>>
iOS-点击图片放大,再次点击返回原视图 类似查看相册的功能
查看>>
JAVA -- stateless4j StateMachine 使用浅析(二)
查看>>
oracle checkpoint
查看>>
KVM虚拟化开源高可用方案(六)ISCSI ON DRBD搭建及常见故障处理
查看>>
android device related
查看>>
iOS 6 Beta3即将发布,iPhone面板谍照已经曝光
查看>>
hadoop 源码包编译
查看>>
关于scrapy的piplines
查看>>
Windows Server 2008 FTP用户目录隔离模式
查看>>
python实现linux下指定目录下文件中的单词个数统计
查看>>
Android源代码下载编译
查看>>
jsp---语句对象Statement
查看>>
RESTful API
查看>>