asp.net Blog Execution (dev, test, release)
HTTP Request & Response

Compression/Decompression (Client & Server side) using GZipStream and pako

What is GZipStream?

GZipStream provides methods and properties used to compress and decompress streams by using the GZip data format specification and support compression of streams with a maximum size of 4GB. GZipStream uses RFC 1952 compression algorithm.

What is pako?

The pako compression library is an open-source JavaScript library to compress and decompress the data. This library can be downloaded from https://github.com/nodeca/pako.

Compressing data using GZipStream

For the Compress function, you need to create a MemoryStream and wrapping it with a using statement so that it is correctly disposed when it leaves scope. We nest a creation of a GZipStream and pass it our MemoryStream and set the compression level to optimal.

Compression using GZipStream and pako

Decompressing data using pako

Let’s suppose we are compressing large data-set at the Server side using GZipStream in order to save bandwidth and now we need to display this compressed data on the UI, we need to decompress the data first and here pako JavaScript library comes into play. The following code snippet decompresses data at the client-side:

Compressing data using pako

Pako can be used to compress data at the client-side to save bandwidth. The following code snipped compress the data at client side:

Client & Server side using GZipStream and pako

Decompressing data using GZipStream

For the Decompress part, we will start with figuring out the length of the uncompressed size by reading the first four bytes of the input array and converting those to an integer. After that, create your resulting output byte array to the uncompressed size. And then again with the MemoryStream and GZipStream, this time you send in the Decompress enum member to specify that we want to decompress the stream.

using GZipStream and pako for compression decompression

I hope this will help if you need to execute compression on the Server-side and then decompression on the Client-side (and vice versa).

Author

admin