7

How can I upload files and get other paramaters of a form? I want to handle multi part requests in Java servlet.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
bhard
  • 81
  • 1
  • 1
  • 2

5 Answers5

12

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 the POST method and the enctype attribute of the form has to be set to multipart/form-data.

<form action="uploadServlet" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>

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:

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
for (String line; (line = reader.readLine()) != null;) {
    System.out.println(line);
}

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!).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for posting info on Servlet 3.0 here as an FYI, even though as you pointed out, it's highly unlikely the asker would be using it. I wasn't aware the 3.0 spec finally filled this gaping hole. – Justin Searls Feb 06 '10 at 18:36
  • BufferedReader reader = request.getReader(); //..a bit shorter – h3xStream Jul 03 '10 at 16:01
  • To use Servlet 3.0 we need web server that supports Java EE 6.0... which would you advise?? Does tomcat support it...? Or is GlassFish V3 a better option when we use Java SE 6.0 – Sangeet Menon Feb 25 '11 at 21:23
  • @S.M.09 You don't explicitly need JEE6. Just a Servlet 3.0 container is enough. For example Tomcat 7.0. You can of course also go ahead with Glassfish 3. It also supports Servlet 3.0. – BalusC Feb 25 '11 at 21:25
  • Does tomcat 6.0.26 support the Servlet3.0....??? I successfully did upload file and some parameters to servers with Glassfish v3....I used `javax.servlet.http.Part=request.getPart()` to get file and a filename I passed.... But that didn't work when I switched to tomcat 6.0.26 from glasfish 3... – Sangeet Menon Feb 25 '11 at 22:14
  • 1
    @S.M.09 Tomcat 6.0 is not the same as Tomcat 7.0 :) http://tomcat.apache.org/whichversion.html – BalusC Feb 25 '11 at 22:22
5

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.

Justin Searls
  • 4,789
  • 4
  • 45
  • 56
2

Step-1

set enctype form tag attribute.

<form enctype="multipart/form-data" ....>
   <input type="file" id="file1" name="file"/>
   .... other stuff
</form>

Step-2

Read Justin's post.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 5
    please, could you describe your step-2 more precisely "Read Justin's post **step 2**". I am stuck in an infinite loop. Thanks. – Hubert Feb 04 '10 at 14:14
  • +1 Thanks for comment. The second step describes the use of **Commons FileUpload** API. – KV Prajapati Feb 05 '10 at 01:48
1

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.

public class UploadServlet extends HttpServlet 
{  

    public void doPost(HttpServletRequest request, HttpServletResponse response)                     throws ServletException, IOException 
    {           
        MultipartRequest m=new MultipartRequest(request,"d:/new");  
        out.print("successfully uploaded");  
    }  
}  

this will upload your file to d:/new

Now to retrive parameter of multipart request you have to use FilenameUtils class and getOriginalFileName() method of MultipartRequest class.

String file = FilenameUtils.getName(req.getOriginalFileName("myfile"))+"\\";
String message = req.getParameter("message");
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
0

This does not work for IE7 and below. Apparently you need to add another attribute to your form encoding ="multipart/form-data"