Skip to content Skip to sidebar Skip to footer

Not Able To Upload File On Tomcat Server Through Servlet Code

I have been trying to upload a file to a Tomcat server through a servlet, but without success. I am able to create a directory, but somehow the servlet code is not creating a file

Solution 1:

Your Content-Disposition header is wrong. It says post-data while it has to be form-data in case of multipart/form-data. Fix it accordingly in your client:

dos.writeBytes("Content-Disposition: form-data; name=uploadedfile;filename="
                     + exsistingFileName + "" + lineEnd);

See also:


Unrelated to the concrete problem, storing uploaded files in the webapp's deploy folder is absolutely a bad idea. They'll all get lost whenever you redeploy a new version of the webapp, with the simple reason that all those so far uploaded files are for sure not contained in the original WAR. Store them somewhere else outside the deploy folder. Just do not ever use getRealPath(), it'll only lead to poor practices.

Further, FileInputStream#available() absolutely doesn't do what you thought there in your code. Get rid of it and just do the usual read-write in a for loop with a fixed buffer size, e.g. 10KB.

Also, using DataOutputStream here is scary. It serves a different purpose (creating .dat files) and in this particular construct there's a big risk for character encoding related issues. Just use PrintWriter which you wrap around OutputStreamWriter with a specified charset. Note that a complete example is shown in the above "See also" link.

Post a Comment for "Not Able To Upload File On Tomcat Server Through Servlet Code"