This question already has an answer here:
How can I upload files and get other paramaters of a form? I want to handle multi part requests in Java servlet.
This question already has an answer here:
How can I upload files and get other paramaters of a form? I want to handle multi part requests in Java servlet.
Step-1
set enctype form tag attribute.
Step-2
Read Justin's post.
To deal with enctype="multipart/form-data" we can not use request.getParameter() directly
Now to deal with the problem
Now, for uploading a file to the server, there can be various ways. But, I am going to use MultipartRequest class provided by oreilly. For using this class you must have cos.jar file.
this will upload your file to d:/new
Now to retrive parameter of multipart request you have to use
FilenameUtils
class andgetOriginalFileName()
method ofMultipartRequest
class.To browse and select a file for upload you need a
<input type="file">
field in the form. As stated in the HTML specification you need to use thePOST
method and the enctype attribute of the form has to be set tomultipart/form-data
.After submitting such a form the form data is available in multipart format in the
HttpServletRequest#getInputStream()
. For testing(!) purposes you can read the stream using the following snippet:You however need to parse the stream byte by byte (instead of char by char). Prior to the fresh new Servlet 3.0 API, the standard Servlet API didn't provide any builtin facilities to parse them. The normal form fields are also not available the usual
request.getParameter()
way, they are included in the multipart form data stream.If you're not on Servlet 3.0 yet (which is only bit less than 2 monts old), then you need to parse the stream yourself. Parsing such a stream requires precise background knowledge of how multipart form data requests are specified and structured. To create a perfect multipart parser you'll have to write a lot of code. But fortunately there's the Apache Commons FileUpload which has proven its robustness with years. Carefully read both the User Guide and Frequently Asked Questions to find code examples and learn how to use it to an optimum degree (take MSIE into account!).
Step 1
Read adatapost's post.
Step 2
Check out the Apache Commons FileUpload project.
There's a similarly workable solution by O'Reily, but its license of use requires you buy a book, and even that requirement is so poorly articulated that I won't benefit it with yet another link.
This does not work for IE7 and below. Apparently you need to add another attribute to your form encoding ="multipart/form-data"