2016-12-28 71 views
1

我正在嘗試使用servlet和JSP上傳圖像上傳ServletFileUpload使用servlet和JSP上傳文件時出現parseRequest()編譯錯誤

我的JSP頁是相當簡單的,並且具有唯一的以下形式:

<form method="post" action="${pageContext.request.contextPath}/uploader" enctype="multipart/form-data"> 
    <input type="file" name="file" value="Select an image..." /> 
    <input type="submit" value="Upload Now" /> 
</form> 

相應servlet和servlet映射在web.xml進行說明。
而我doPost方法看起來:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    PrintWriter out = response.getWriter(); 

    FileItemFactory itemFactory = new DiskFileItemFactory(); 
    ServletFileUpload upload = new ServletFileUpload(itemFactory); 

    if (!contentType.equals("image/png")) { 
     out.println("Only PNG image files supported."); 
     continue; 
    } 

    try { 
     List<FileItem> items = upload.parseRequest(request); // here is an error 
     for (FileItem item : items) { 
      String contentType = item.getContentType(); 

      File uploadDir = new File(UPLOAD_DIR); 
      File file = File.createTempFile("img", ".png", uploadDir); 

      item.write(file); 

      out.println("File uploaded."); 
     } 
    } catch (FileUploadException e) { 
     out.println("Upload failed."); 
     return; 
    } 
} 

但是,編譯以下行抱怨:List<FileItem> items = upload.parseRequest(request);

在文件FileUploadBase方法parseRequest(RequestContext)是不適用的參數(HttpServletRequest的)。

雖然在回答How to upload files to server using JSP/Servlet?這種方法不會產生任何錯誤:如果我在這裏看到org.apache.commons.fileupload 請求應ServletRequestContext不HttpServletRequest的

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); 

回答

1

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(new ServletRequestContext(request)); 
+0

絕對正確!非常感謝。 – DimaSan

+0

不客氣。 –

0

此代碼應該解決問題

DiskFileItemFactory diskFactory = new DiskFileItemFactory(); 
diskFactory.setSizeThreshold(4000); 
diskFactory.setRepository(new File(System.getProperty("java.io.tmpdir"))); 
ServletFileUpload uploadHandler = new ServletFileUpload(diskFactory); 
List<FileItem> items = upload.parseRequest(request); 
相關問題