2013-01-21 23 views
6

Đoạn mã html gửi một yêu cầu post tới servlet có tên servlet. Yêu cầu là loại multipart/form-data. Nhưng servlet không tìm thấy gì và in null cho tên của phần mà tôi cố truy xuất. Tại sao vậy ?tại sao servlet không lấy phần này? Nó hiển thị null dưới dạng tên tệp

<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 
} 
+0

thể trùng lặp của [Làm thế nào để upload file lên máy chủ sử dụng JSP/Servlet?] (Http://stackoverflow.com/questions/2422468/how-to-upload-files -to-server-using-jsp-servlet) –

+0

BalusC đã viết một câu trả lời tuyệt vời cho [câu hỏi SO liên quan] (http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using -jsp-servlet) liên quan đến Tải lên tệp bằng Serlvet 3.0. –

Trả lời

14

Nếu bạn muốn sử dụng Servlet 3.0 HttpServletRequest#getParts() phương pháp, sau đó bạn phải chú thích servlet của bạn với @MultipartConfig.

Ví dụ:

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

} 
+0

Làm thế nào có thể thực hiện trong trường hợp Servlet <3.0 là Servlet cụ thể 2.5 – Chaitanya

+2

Nó hoạt động như ma thuật. –

Các vấn đề liên quan