java web中servlet實現post方法上傳多文件數據接收

最近一直看java web如何實現sverlet接收post一次上傳的多文件數據。目前找到親測靠譜的實現方法,已經在項目中跑過可用。
需要用到的jar包:
commons-fileupload-1.3.2.jar(http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi)
commons-io-2.5.jar(http://commons.apache.org/io/download_io.cgi)
代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	request.setCharacterEncoding("utf-8");//防止中文名亂碼  
        int sizeThreshold=1024*6; //緩存區大小  
        String basePath = this.getServletContext().getRealPath("/upload/");
        System.out.println(basePath);
        File repository = new File(basePath); //緩存區目錄  
        long sizeMax = 1024 * 1024 * 2;//設置文件的大小爲2M  
        final String allowExtNames = "jpg,gif,bmp,rar,rar,txt,docx,png";  
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();  
        diskFileItemFactory.setRepository(repository);  
        diskFileItemFactory.setSizeThreshold(sizeThreshold);  
        ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);  
        servletFileUpload.setSizeMax(sizeMax);  
          
        List<FileItem> fileItems = null;  
        try{  
            fileItems = servletFileUpload.parseRequest(request);  
              
            for(FileItem fileItem:fileItems){  
                long size=0;  
                String filePath = fileItem.getName(); 
                System.out.println(filePath);  
                if(filePath==null || filePath.trim().length()==0)  
                    continue;  
                String fileName=filePath.substring(filePath.lastIndexOf(File.separator)+1);   
                String extName=filePath.substring(filePath.lastIndexOf(".")+1);   
                if(allowExtNames.indexOf(extName)!=-1)  
                {  
                    try {  
                        fileItem.write(new File(basePath+File.separator+fileName));  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
                else{  
                    throw new FileUploadException("file type is not allowed");  
                }  
            }  
        }catch(FileSizeLimitExceededException e){  
            System.out.println("file size is not allowed");  
        }catch(FileUploadException e1){  
            e1.printStackTrace();  
        }  
	response.setContentType("text/html");
	response.setCharacterEncoding("utf-8");
	PrintWriter out = response.getWriter();
	out.println("this is Post method");
	out.flush();
	out.close();
}

項目結構:

服務器一次post上傳存儲結果:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章