2014-12-02 125 views
0

我想上傳文件使用java web應用程序使用DiskFileItemFactory。但問題是它沒有得到任何文件。它顯示迭代中的空數組。我上傳文件與DiskFileItemFactory.But文件不上傳使用Java

iter.size()是0. 請參閱下面的我的代碼。

public ModelAndView upload(ModelMap model, HttpSession session, HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException, FileUploadException { 
if (ServletFileUpload.isMultipartContent(request)) { 

    System.out.println("file available"); 
} 

boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
if (isMultipart) { 
    // ResourceImpl resource = new ResourceImpl(); 
    try { 
     //Create a factory for disk-based file items 
     FileItemFactory factory = new DiskFileItemFactory(); 
     ServletFileUpload upload = new ServletFileUpload(factory); 
     List items = upload.parseRequest(request); 
     System.out.println(items.size()); 
     Iterator iter = items.iterator(); 
     while (iter.hasNext()) { 

      FileItem item = (FileItem) iter.next(); 
     } 

    } catch (Exception e) { 

    } 
} 

我的表單是;

<form method="post" action="/DropBox/upload.html" enctype="multipart/form-data"> 
    Select file to upload: <input type="file" name="uploadFile" /> 
    <br/><br/> 
    <input type="submit" value="Upload" /> 
</form> 

我在哪裏做錯了。 plaese幫助我。 thanq。

+0

沒有足夠的信息。 – Tiny 2014-12-02 10:20:02

+0

現在檢查它到這裏問題列表項目= upload.parseRequest(請求).Sows 0 siz。 – kamesh 2014-12-02 10:29:57

+0

它是否有所作爲,如果您使用通用類型聲明列表,例如'List items = upload.parseRequest(request);'?順便說一句,這是一個關於使用Servlet API上傳文件的詳細[答](http://stackoverflow.com/a/2424824/1391249)。 – Tiny 2014-12-02 11:06:19

回答

0

你應該爲每個嘗試。它做得很好。

if (ServletFileUpload.isMultipartContent(request)) { 

    try { 
     List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); 

     for (FileItem item : multipart) { 

      if (!item.isFormField()) { 

       filename = new File(item.getName()).getName(); 
       folder = "path"; 
       File file = new File(folder); 

       if (!file.exists()) { 
        file.mkdir(); 

       } 
      } 

      item.write(new File(folder + "/" + filename)); 
     } 
    } 
}