2014-04-03 110 views
2

這是文件的代碼上傳處理器 這是工作的罰款我的服務器上,但在上傳文件後,它只顯示文件被成功
上傳的,但我也想顯示其上傳的文件名文件上傳處理

import java.io.File; 
import java.io.IOException; 
import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 

public class FileUploadHandler extends HttpServlet { 
private final String UPLOAD_DIRECTORY = "C:/uploads"; 

@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    //process only if its multipart content 
    if(ServletFileUpload.isMultipartContent(request)){ 
     try { 
      List<FileItem> multiparts = new ServletFileUpload(
            new DiskFileItemFactory()).parseRequest(request); 

      for(FileItem item : multiparts){ 
       if(!item.isFormField()){ 
        String name = new File(item.getName()).getName(); 
        item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); 
       } 
      } 

    //File uploaded successfully 

      request.setAttribute("message", "File Uploaded Successfully"); 
     } catch (Exception ex) { 
      request.setAttribute("message", "File Upload Failed due to " + ex); 
     }   

    }else{ 
     request.setAttribute("message", 
          "Sorry this Servlet only handles file upload request"); 
    } 

    request.getRequestDispatcher("/done.jsp").forward(request, response); 

} 

} 
+0

是文件實際上傳的嗎?你只是錯過了文件名?在這種情況下,它可能是阿拉伯字符未在瀏覽器中顯示的編碼問題 – Loopo

回答

1

item.getName()存儲在變量中供以後使用。由於您正在使用循環,因此如果有多個文件名,您將不得不跟蹤多個文件名。

String fileNames = ""; //to keep list of filenames 
    for(FileItem item : multiparts){ 
      if(!item.isFormField()){ 
       fileNames += item.getName() + "; "; //add filename to string 
       String name = new File(item.getName()).getName(); 
       item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); 
      } 
     } 
    ..... 
    ..... 
    request.setAttribute("message", "File(s) Uploaded Successfully: " + fileNames); 
0

此代碼可能對您有所幫助!

private static String getFileName(Part part) { 
    for (String cd : part.getHeader("content-disposition").split(";")) { 
     if (cd.trim().startsWith("filename")) { 
      String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); 
      return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix. 
     } 
    } 
    return null; 
}