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-dataencoding. 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 namesname1,name2andname3which have the valuesvalue1,value2andvalue3filled):With a single
<input type="file">field with the namefile1the entire request body look like this: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 usedrequest.getPart()instead to get the sole file content.If you’re still on servlet 2.5 or older, then you can use among others Apache Commons FileUpload to parse it.
See also: