8

html片段向命名的servlet发送post请求。请求的类型是. 但是 servlet 什么也没找到,并为我尝试检索的部分的名称打印 null。这是为什么 ?servletmultipart/form-data

<form method="post" action="servlet" enctype="multipart/form-data">
        <input type="file" value="browse" name="FileShared" />
        <input type="submit" value="submit" />
 </form>

import javax.servlet.http.Part;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    //String fileName = request.getPart("FileShared").getName(); 
    // Throws a nullpointer exception if I don't comment the above statement
    PrintWriter writer = response.getWriter();
    //writer.println(fileName);
    Collection<Part> c = request.getParts();
    Iterator i = c.iterator();
    while(i.hasNext()) {
        writer.println("Inside while loop"); // This statement never gets printed
        writer.println(i.next());
    }
    writer.println("outside while loop"); // Only this statement gets printed
}
4

1 回答 1

14

如果你想使用 Servlet 3.0HttpServletRequest#getParts()方法,那么你必须用@MultipartConfig.

例子 :

@WebServlet(urlPatterns={"/SampleServlet"})
@MultipartConfig
public class SampleServlet extends HttpServlet {

}
于 2013-01-21T08:44:20.077 回答