1. 程式人生 > >java檔案上傳的兩種方式的一些問題

java檔案上傳的兩種方式的一些問題

接觸到一個專案,一個java web專案,據說是十幾年的寫的程式碼,現在打算做新版本,先要我們專案組解決一下就版本程式碼裡面的bug,以便現在的日常使用。

主要的bug是檔案上傳失敗

打斷點跟蹤了一下,發現了問題:SpringMVC中servletFileUpload.parseRequest(request)解析為空獲取不到資料問題

程式碼中在控制器裡面自己完成request的解析,又在Spring MVC檔案加入了上傳配置的multipartResolver,直接註釋這個配置,就可以用了

然而,在測試其他地方的上傳下載時,發現其他地方的不可用了,再次閱讀原始碼,發現了問題,因為程式碼利用使用了兩種版本的上傳,其他地方的上傳需要用到SpringMVC的配置的multipartResolver

所以現在的解決辦法就是統一,要麼都使用SpringMVC裡面的配置,要麼都自己在控制器裡面解析request

這裡嘗試了第二種(下面程式碼只針對上傳excel表格,因為程式碼中這個位置只需要上excel)

修改前,需要SpringMVC配置multipartResolver

@RequestMapping("/regist111")
public String regist(@RequestParam(value="file") MultipartFile 
       file,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		 // 判斷檔案是否為空  
		String filePath = null;
		File fileNew = null;
		if (file == null || file.isEmpty()) {
			String Msg = "請輸入xls檔案!";
			request.getSession().setAttribute("msg", Msg);
			return "admin/userRegist/index";

		}
        if (!file.isEmpty()) {  
        	
            try {  
                // 檔案儲存路徑  
                filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  
                        + file.getOriginalFilename();  
                System.out.println(filePath);
                java.io.File fileExists=new java.io.File(filePath);
                if(!fileExists.exists()){
                	fileExists.mkdirs();
        		 }
                // 轉存檔案  
                fileNew = new File(filePath);
                //file.transferTo(new File(filePath));  
                file.transferTo(fileNew);
                System.out.println(fileNew.getName().substring(fileNew.getName().lastIndexOf(".")+1));
                if(!fileNew.getName().substring(fileNew.getName().lastIndexOf(".")+1).equals("xls")){
                	String Msg = "請輸入xls檔案!";
        			request.getSession().setAttribute("msg", Msg);
        			return "admin/userRegist/index";
                }
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
     return "admin/userRegist/index";
	}

修改後,註釋SpringMVC配置multipartResolver

@RequestMapping("/regist")
public String regist1(HttpServletRequest request, HttpServletResponse response) throws Exception{
		// 判斷檔案是否為空
		if (!ServletFileUpload.isMultipartContent(request)) {
			String Msg = "請輸入xls檔案!";
			request.getSession().setAttribute("msg", Msg);
			return "admin/userRegist/index";
		}
		//建立一個基於硬碟的FileItem工廠
		FileItemFactory factory = new DiskFileItemFactory();
		//建立一個檔案上傳處理器
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		//System.out.println("ldb---------21-------------------");
		// 解析HTTP請求訊息頭
		List items = upload.parseRequest(request);
		Iterator itr = items.iterator();
		String filePath = null;
		File fileNew = null;
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			String fileName = item.getName();
			// 檔案儲存路徑
			filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";

			System.out.println(filePath);
			java.io.File fileExists=new java.io.File(filePath);
			if(!fileExists.exists()){
				fileExists.mkdirs();
			}

			try {
				fileNew = new File(filePath,fileName);
				item.write(fileNew);
			} catch (Exception e) {
				String Msg ="上傳檔案失敗。";
				request.getSession().setAttribute("msg", Msg);
				return "admin/userRegist/index";
			}
			if(!fileNew.getName().substring(fileNew.getName().lastIndexOf(".")+1).equals("xls")){
				String Msg = "請輸入xls檔案!";
				request.getSession().setAttribute("msg", Msg);
				return "admin/userRegist/index";
			}
		}
       return "admin/userRegist/index";
}

拍坑記錄:

1:java.io.FileNotFoundException: .\xxx\xxx.txt (系統找不到指定的路徑。)

2:java.io.FileNotFoundException: .\xx\xx (拒絕訪問。)

當遇到問題1時,的確是當前所指定的檔案不存在或者目錄不存在。 
當遇到第二個問題時,是因為你訪問的是一個檔案目錄,如果這個目錄沒有許可權訪問或者是目錄不存在,就會丟擲問題2的異常。

解決辦法 
第一個的解決辦法是,先判斷一下當前檔案是否存在,如果存在則略過,如果不存在,建立
第二個的解決辦法是,在填寫檔案的路徑時一定要具體到檔案