file corrupted when I post it to the servlet using GZIPOutputStream

前端 未结 1 1149
灰色年华
灰色年华 2021-01-24 01:31

I tried to modify @BalusC excellent tutorial here to send gziped compressed files. This is a working java class :

import java.io.File;
import java.io.FileInputSt         


        
相关标签:
1条回答
  • 2021-01-24 02:24

    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.

    0 讨论(0)
提交回复
热议问题