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:
file-header
is, the only thing I can be sure of is that HTTP headers are not included in the stream returned byreq.getInputStream()
. I assume 'req' is an instance of ServletRequest or the request object in JSP. – neevek