一般的使用流程(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 { /// <summary> /// GZip 壓縮格式 /// </summary> GZip, /// <summary> /// BZip2 壓縮格式 /// </summary> BZip2, /// <summary> /// Zip 壓縮格式 /// </summary> Zip } public class CompressHelper { public static CompressionType CompressionProvider = CompressionType.GZip; #region Public methods /// <summary> /// 從原始字節數組生成已壓縮的字節數組。 /// </summary> /// <param name="bytesToCompress">原始字節數組。</param> /// <returns>返回已壓縮的字節數組</returns> 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(); } /// <summary> /// 從原始字符串生成已壓縮的字符串。 /// </summary> /// <param name="stringToCompress">原始字符串。</param> /// <returns>返回已壓縮的字符串。</returns> public static string Compress(string stringToCompress) { byte[] compressedData = CompressToByte(stringToCompress); string strOut = Convert.ToBase64String(compressedData); return strOut; } /// <summary> /// 從原始字符串生成已壓縮的字節數組。 /// </summary> /// <param name="stringToCompress">原始字符串。</param> /// <returns>返回已壓縮的字節數組。</returns> public static byte[] CompressToByte(string stringToCompress) { byte[] bytData = Encoding.UTF8.GetBytes(stringToCompress); return Compress(bytData); } /// <summary> /// 從已壓縮的字符串生成原始字符串。 /// </summary> /// <param name="stringToDecompress">已壓縮的字符串。</param> /// <returns>返回原始字符串。</returns> 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; } /// <summary> /// 從已壓縮的字節數組生成原始字節數組。 /// </summary> /// <param name="bytesToDecompress">已壓縮的字節數組。</param> /// <returns>返回原始字節數組。</returns> 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 /// <summary> /// 從給定的流生成壓縮輸出流。 /// </summary> /// <param name="inputStream">原始流。</param> /// <returns>返回壓縮輸出流。</returns> 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); } } /// <summary> /// 從給定的流生成壓縮輸入流。 /// </summary> /// <param name="inputStream">原始流。</param> /// <returns>返回壓縮輸入流。</returns> 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<T>(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(); } } } }
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.<number> or Uint8Array var gunzip = new Zlib.Gunzip(compressed); var plain = gunzip.decompress();
下面我寫的一個流程
document.write("<script src='../Gzip/base64.js'></script>");
document.write("<script src='../Gzip/zlib_and_gzip.min.js'></script>");
document.write("<script src='../Gzip/encoding-indexes.js'></script>");
document.write("<script src='../Gzip/encoding.js'></script>");
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){
}
}
相關文件下載鏈接: 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; } };
Gzip的轉碼和解碼(zlib.js庫)
https://github.com/imaya/zlib.js/blob/master/README.en.md
附帶一個編碼轉換庫(text-encoding)
https://github.com/inexorabletash/text-encoding
