upload, Why bigger than the original?

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?


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:

  • How to upload files to server using JSP/Servlet?
  • 链接地址: http://www.djcxy.com/p/46206.html

    上一篇: 上传PDF文件

    下一篇: 上传,为什么比原来大?