5
votes

Servlet doPost handing file-uploads,

    InputStream in = req.getInputStream();

    File file = new File("c:/8.dat");
    OutputStream out = new FileOutputStream(file);
    byte[] buffer = new byte[1024];

    int len =0;
    while((len=in.read(buffer))!=-1){
        out.write(buffer, 0, len);
    }
    bao.close();
    out.close();
    in.close();

Dose Request's getInputStream Method take the http header information?

Why is the uploaded file bigger than the original?

1
getInputStream returns a stream from which you can read the request body(or the uploaded file in your case), the HTTP headers are not included in the stream, they are handled by the framework and you can get those headers from the Request object.neevek
No, I checked the uploaded file, file-header has http header info..skg
I don't know what file-header is, the only thing I can be sure of is that HTTP headers are not included in the stream returned by req.getInputStream(). I assume 'req' is an instance of ServletRequest or the request object in JSP.neevek

1 Answers

8
votes

Sending files in a HTTP request is usually done using multipart/form-data encoding. This enables the server to distinguish multiple form data parts in a single request (it would otherwise not be possible to send multiple files and/or input fields along in a single request). Each part is separated by a boundary and preceeded by form data headers. The entire request body roughly look like this (taking an example form with 3 plain <input type="text"> fields with names name1, name2 and name3 which have the values value1, value2 and value3 filled):

--SOME_BOUNDARY
content-disposition: form-data;name="name1"
content-type: text/plain;charset=UTF-8

value1
--SOME_BOUNDARY
content-disposition: form-data;name="name2"
content-type: text/plain;charset=UTF-8

value2
--SOME_BOUNDARY
content-disposition: form-data;name="name3"
content-type: text/plain;charset=UTF-8

value3
--SOME_BOUNDARY--

With a single <input type="file"> field with the name file1 the entire request body look like this:

--SOME_BOUNDARY
content-disposition: form-data;name="file1";filename="some.ext"
content-type: application/octet-stream

binary file content here
--SOME_BOUNDARY--

That's thus basically what you're reading by request.getInputStream(). You should be parsing the binary file content out of the request body. It's exactly that boundary and the form data header which makes your uploaded file to seem bigger (and actually also corrupted). If you're on servlet 3.0, you should have used request.getPart() instead to get the sole file content.

InputStream content = request.getPart("file1").getInputStream();
// ...

If you're still on servlet 2.5 or older, then you can use among others Apache Commons FileUpload to parse it.

See also: