views:

81

answers:

1

I am tring to retrieve a filename or the file itself for use in a java servlet (from a web form).

I have a file form field:

<form enctype="multipart/form-data" method="post" action="SaveDictionary.do">
    <label>
        <input type="file" name="dictionary_file" id="dictionary_file" />
        <br />
    </label>
    <label>
        <br />     
        <input type="submit" name="saveDic" id="saveDic" value="Save Dictionary" />
    </label>
 </form>

I wanto then process it in my servlet, what do I do to process this - for a normal text field I would use something like

String myValue = (String) request.getParameter("parameter_name");

Assuming I have this class, what do I put in the doPost() method to get either the file path or the actual file contents.

@SuppressWarnings("serial")
public class SaveDictionary extends HttpServlet {

    public void doPost(HttpServletRequest request,
  HttpServletResponse response) throws IOException, ServletException {

     // I can't work out what goes here, the same
     // String myValue = (String) request.getParameter("parameter_name"); doesn't work

     response.sendRedirect("dictionary.jsp");
    }

}
+1  A: 

Multipart/form-data encoded requests are not supported by the default servlet API. You basically need to parse the request body yourself based on the HttpServletRequest#getInputStream(). But that's a precious and tedious work. You don't want to do that if you're already asking this question here at SO. Fortunately there's already a robust, thoroughly developed and maintained API out for that, the Apache Commons FileUpload API. It's in fact easy to use. You can find examples in their User Guide and tips&tricks in their FAQ.

You can also wrap it in a Filter which does all the parsing work and puts all the parameters back in the request, so that it's all transparent in the servlet code and you can continue using HttpServletRequest#getParameter() and consorts the usual way. Uploaded files can then be obtained as request attributes. Here's a basic example.

Hope this helps.

BalusC