Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress string in Sql server and decompress in javascript

I want to transfer a long string from my database to my webpage. So, I want to try the approach of compressing my string in my server and decompress it in client side.

So far I have this in my sql server codes:

select compress('this is just a sample string')

which returns this:

0x1F8B08000000000004002BC9C82C5600A2ACD2E212854485E2C4DC829C5485E292A2CCBC7400206D53921C000000

Now I need a function in my javascript to revert the compression operation :

var str = "0x1F8B08000000000004002BC9C82C5600A2ACD2E212854485E2C4DC829C5485E292A2CCBC7400206D53921C000000";
alert(decompressed(str));

which should alert "this is just a sample string".

like image 595
Behnam Avatar asked Oct 24 '25 10:10

Behnam


2 Answers

First, let me explain the difference between how VARBINARY(MAX) is stored and displayed in SSMS.
String "0x1F8B0800000000000..." is a hexadecimal representation created by SSMS of varbinary data stored in the database. The underlain binary value is mostly unprintable characters. So if you try to use this string in your java code it just can't work directly.

I created an example here, if you press "STEP" button, you will see real value: HexToBin

That is why you second example will not work, you need to read byte array from database and then use this byte array in zlib.

There is a good example how to use deflate in java: Java Decompress a string compressed with zlib deflate

like image 101
Piotr Palka Avatar answered Oct 27 '25 00:10

Piotr Palka


Maybe you want something like this: https://jsfiddle.net/58mgsy9a/

const parseString = str => {
    const strWithoutprefix = str.slice(2);
    const array = strWithoutprefix.match(/.{1,2}/g);
    return array.map(pair => parseInt(pair, 16));
};

const decompressed = gzipArray => {
    const gunzip = new Zlib.Gunzip(gzipArray);
    const plain = gunzip.decompress();
    return String.fromCharCode(...plain);
};

var str = "0x1F8B08000000000004002BC9C82C5600A2ACD2E212854485E2C4DC829C5485E292A2CCBC7400206D53921C000000";
alert(decompressed(parseString(str)));

The parseString function takes your input string and converts it to an array of numbers, because zlib expects an array of numbers as the input. Then the decompressed function uses zlib to unzip the array. The decompress function of zlib returns an array of number, so we convert it back to a string.

like image 41
Garuno Avatar answered Oct 26 '25 23:10

Garuno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!