上傳文件的方法有很多種,我現在做的項目是使用Apache的fileupload。
首先我們需要commons-fileupload-1.3.1.jar的包。 maven在pom.xml導入,普通web項目放在WEB-INF的lib目錄下
然后 commons-fileupload.jar 依賴於commons-io.jar,所以同理加入commons-fileupload.jar
下面是代碼。 用的是spring mvc,功能在controller里實現
重新寫了一遍注釋,代碼應該能看的很清楚了
/* * 接收上傳的文件,返回文件地址 */ //url 地址 @RequestMapping("/uploadify") public void uploadFile(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { String type = request.getParameter("type"); String ret_fileName = null;// 返回給前端已修改的圖片名稱 // 臨時文件路徑 String dirTemp = "/static/upload/temp"; //圖片存儲相對路徑 String suitelogo = ""; //設置圖片存儲相對路徑 //這里的type是前台傳過來方便辨認是什么圖片的參數,沒有需要就不用判斷 if ("app".equals(type)) { suitelogo = "/static/upload/applogo"; } else if ("suite".equals(type)) { suitelogo = "/static/upload/suitelogo"; } else { suitelogo = dirTemp; } request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); // 獲取當前項目的根目錄 tomcat的絕對路徑/webapps/項目名 String realPath = session.getServletContext().getRealPath(""); //獲取tomcat下的ROOT目錄,通過root絕對路徑和存儲圖片文件夾的相對路徑創建目錄 //mkdirs方法逐級創建目錄。 mkdir只創建最后一級目錄,前面目錄不存在則不創建 File realFile = new File(realPath); String rootPath = realFile.getParent() + "/ROOT"; String normPath = rootPath + suitelogo; String tempPath = rootPath + dirTemp; File f = new File(normPath); File f1 = new File(tempPath); System.out.println(normPath); if (!f.exists()) { f.mkdirs(); } if (!f1.exists()) { f1.mkdirs(); } //創建文件解析對象 DiskFileItemFactory factory = new DiskFileItemFactory(); //設定使用內存超過5M時,將產生臨時文件並存儲於臨時目錄中 factory.setSizeThreshold(5 * 1024 * 1024); // 設定存儲臨時文件的目錄 factory.setRepository(new File(tempPath)); //創建上傳文件實例 ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { //解析request 成FileItem 因為支持多個文件上傳,所以用list List<?> items = upload.parseRequest(request); Iterator<?> itr = items.iterator(); while (itr.hasNext()) { //獲取文件名 FileItem item = (FileItem) itr.next(); String fileName = item.getName(); if (fileName != null) { fileName = fileName.substring(fileName.lastIndexOf("/") + 1); fileName = getUUID() + fileName; ret_fileName = normPath + "/"+fileName; } //如果不是普通表單,則是文件上傳表單,取二進制流寫入本地 if (!item.isFormField()) { try { File uploadedFile = new File(normPath + "/" + fileName); OutputStream os = new FileOutputStream(uploadedFile); InputStream is = item.getInputStream(); byte buf[] = new byte[1024];// 可以修改 1024 以提高讀取速度 int length = 0; while ((length = is.read(buf)) > 0) { os.write(buf, 0, length); } // 關閉流 os.flush(); os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } } } } catch (FileUploadException e) { e.printStackTrace(); } // 將已修改的圖片名稱返回前台 out.print(ret_fileName); out.flush(); out.close(); } //生成隨機數字,防止文件重名 private String getUUID() { return UUID.randomUUID().toString(); }
流程主要幾個步驟
1.創建文件解析對象DiskFileItemFactory factory = new DiskFileItemFactory();
2.創建上傳文件實例ServletFileUpload upload = new ServletFileUpload(factory);
3獲取上傳的文件明,並把文件存入本地