1. 程式人生 > >檔案上傳 commons-fileupload

檔案上傳 commons-fileupload

匯入兩個jarcommons-fileupload.jar,和commons-io.jar


首先是上傳頁面

fileupload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'fileUpload.jsp' starting page</title>
  </head>
  
  <body>
<form action="../servlet/FileUpload" method="post" enctype="multipart/form-data">  
<br>  
  檔案一:<input type="file" name="file1" /> <br>  
   檔案二:<input type="file" name="file2" /> <br>  
  上傳者: <input type="text" name="uploader"/> <br>  
      日期: <input type="text" name="date"/> <br>  
        <input type="submit" value="提交"/>  
   
</form>  
  </body>
</html>


傳如servlet 處理



public class FileUpload extends HttpServlet {


  private static final long serialVersionUID = 1L;  
  private static final String fileDir = "F:/";  

/**
* Constructor of the object.
*/
public FileUpload() {
super();
}


/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
doPost();

}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//設定編碼
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

//核心程式碼
try {  
           DiskFileItemFactory fileFactory = new DiskFileItemFactory();    //產生工廠
           ServletFileUpload fu = new ServletFileUpload(fileFactory);      //呼叫工具
           fu.setFileSizeMax(30*1024*1024);  //設定檔案大小限制


           List fileItems = fu.parseRequest(request);    // 獲取請求項
           Iterator iter = fileItems.iterator();  
           String uploader = null;  
           String date = null;  
           List<String> fileNames = new ArrayList<String>();  
           while (iter.hasNext()) {  
               FileItem item = (FileItem) iter.next();  
           
               
               if (!item.isFormField()) { //  判斷檔案  
                   String oldFileName = item.getName();  
                   String fieldName = item.getFieldName();
                   String content = item.getString();
                   String type = item.getContentType();
                   
                   String newFileName = null;  
                  //  System.out.println("fileName :" +oldFileName +" and fileName : "+ fieldName + "  and content :" + content + " and type "+ type);
                   int delimiter = oldFileName.lastIndexOf("/"); 
                  //  System.out.println(delimiter);
                   
                   if (delimiter == -1)  {
                       newFileName = oldFileName.substring(delimiter + 1);
                       System.out.println(newFileName);
                   }else{ 
                       newFileName = oldFileName; 
                   }
                   if(newFileName != null && !newFileName.trim().equals("")){
                    fileNames.add(newFileName);  
                    item.write(new File(fileDir + "first.txt"));            // 設定寫入地址,自己設定
                   }
               } else { // 表單  
                   String fieldName = item.getFieldName();  
                   if ("uploader".equals(fieldName)) {  
                       uploader = item.getString();  
                   } else if ("date".equals(fieldName)) {  
                       date = item.getString();  
                   }  
               }  
               }
            
           System.out.println("forword");
       //     request.setAttribute("fileNames",fileNames);  
       //   request.getRequestDispatcher("../admin/fileUploadResult.jsp").forward(request, response);      // 後續處理
       } catch (Exception e) {  
 
       }  
   }  



/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}


}