Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GZip a string for output from Coldfusion results in "Content Encoding Error" in browsers

I am trying to GZip content in a variable to output to the browser. To start I am making this very simple and not worrying about browsers that do not support gzip. Also I have put this together from researching several methods that I could find on the web. Some of them from people that may be reading this question.

<cfsavecontent variable="toGZIP"><html><head><title>Test</title></head><body><h1>Fear my test</h1></body></html></cfsavecontent>

<cfscript>
ioOutput = CreateObject("java","java.io.ByteArrayOutputStream");
gzOutput = CreateObject("java","java.util.zip.GZIPOutputStream");

ioOutput.init();
gzOutput.init(ioOutput);

gzOutput.write(toGZIP.getBytes("UTF-8"), 0, Len(toGZIP.getBytes()));

gzOutput.finish();
gzOutput.close();
ioOutput.flush();
ioOutput.close();

toOutput=ioOutput.toString("UTF-8");
</cfscript>

<cfcontent reset="yes" /><cfheader name="Content-Encoding" value="gzip"><cfheader name="Content-Length" value="#ArrayLen( toOuptut.getBytes() )#" ><cfoutput>#toOuptut#</cfoutput><cfabort />

But I get an error in Firefox (and chrome and Safari)

Content Encoding Error

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

Anybody have any ideas?

OS: Mac OX-X Snow Leopard
CF: 9-Dev
Webserver: Apache


SOLUTION

<cfsavecontent variable="toGZIP"><html><head><title>Test</title></head><body><h1>Fear my test</h1></body></html></cfsavecontent>

<cfscript>
ioOutput = CreateObject("java","java.io.ByteArrayOutputStream");
gzOutput = CreateObject("java","java.util.zip.GZIPOutputStream");

ioOutput.init();
gzOutput.init(ioOutput);

gzOutput.write(toGZIP.getBytes(), 0, Len(toGZIP.getBytes()));

gzOutput.finish();
gzOutput.close();
ioOutput.flush();
ioOutput.close();

toOutput=ioOutput.toByteArray();
</cfscript>

<cfheader name="Content-Encoding" value="gzip"><cfheader name="Content-Length" value="#ArrayLen(toOutput)#" ><cfcontent reset="yes" variable="#toOutput#" /><cfabort />
like image 692
Tyler Clendenin Avatar asked Sep 12 '10 05:09

Tyler Clendenin


1 Answers

The follow line look completely wrong:

toOutput=ioOutput.toString("UTF-8");

You encode the GZip stream with UTF8. The result are garbage data. The best you set the GZip data as binary if ColdFusion has the option. If you can only set a string then you need an encoding that not change any bytes. For example iso1.

like image 101
Horcrux7 Avatar answered Sep 18 '22 02:09

Horcrux7