English 中文(简体)
Using a file form field with a Java servlet
原标题:

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");
    }

}
最佳回答

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.

问题回答

暂无回答




相关问题
Can t access locally hosted project via the internet?

I m currently developing a Java Servlet Project in Eclipse. The project is compiled via Tomcat 5.5 and hosted in localhost:8080(alternatively 127.0.0.1:8080 AND 192.168.1.10:8080 which also happens ...

JSP programmatically render

I need to programmatically render JSP page. As far as I understand, JSP should have some compiler. The question is can I use this compiler dirrectly without JspServlet and others? All I need is ...

Javascript redirect

I am working with javascript and here is what I am trying to do: 1. Send a get request which looks like "http://localhost:8080/myapp/verify.htm?verifyId=Agkvhs" My requests reaches my verify.jsp in ...

热门标签