file corrupted when I post it to the servlet using GZIPOutputStream

自作多情 提交于 2019-12-02 05:50:32

You need to call

((GZIPOutputStream)output2).finish();

before flushing. See the javadoc here. It states

Finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Which is what you are doing. So

for (int length = 0; (length = input.read(buffer)) > 0;) 
    output2.write(buffer, 0, length);
}
((GZIPOutputStream)output2).finish(); //Write the compressed parts
// obviously make sure output2 is truly GZIPOutputStream
output2.flush(); // 

On the subject of applying multiple filters in succession to the same output stream, this is how I understand it:

You have an OutputStream, that is a socket connection, to the HTTP server. The HttpUrlConnection writes the headers and then you write the body directly. In this situation (multipart), you send the boundary and headers as unzipped bytes, the zipped file content, and then again the boundary. So the stream looks like this in the end:

                            start writing with GZIPOutputStream
                                          v
    |---boundary---|---the part headers---|---gzip encoded file content bytes---|---boundary---|
    ^                                                                           ^
write directly with PrintWriter                                      use PrintWriter again

So you can see how you have different parts written in succession with different filters. Think of the PrintWriter as an unfiltered filter, anything you give it is written directly. The GZIPOutputStream is a gzip filter, it encodes (gzips) the bytes it's given.

As for the source code, look in your Java JDK installation, you should have a src.zip file that contains the public source code, java.lang*, java.util.*, java.io.*, javax.*, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!