1、准備上傳下載的api組件
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2、編寫前台上傳表單
<form action="index/newadd" method="post" enctype="multipart/form-data"> <table class="form"> <tr> <td class="field">證件照:</td> <td><input type="file" id="wkpicpath" class="text" name="attachs" /> </td> <td class="field"id="hderrorinfo" style="margin-left:0px">${sessionScope.uploadwkError}</td> </tr> <tr> <td class="field">頭像:</td> <td><input type="file" id="hdpicpath" class="text" name="attachs" /></td> <td class="field"id="hderrorinfo" style="margin-left:0px">${sessionScope.uploadhdError}</td> </tr> <tr> <td></td> <td><label class="ui-blue"><input type="submit" name="submit" value="添加" /></label></td> </tr> </table> </form>
3、編寫controller層(多文件上傳)
/* * 管理員新增用戶 */ @RequestMapping(value="/newadd",method=RequestMethod.POST) public String doAddUser(HttpSession session,HttpServletRequest request, @RequestParam(value="attachs",required=false)MultipartFile[] attachs, User user){ //定義兩個上傳文件的路徑 String wkpicpath = null; String hdpicpath = null; String errorinfo = null; //定義上傳過程管理標記 boolean flag = true; //定義文件保存的位置 String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); //循環讀取文件信息 for(int i=0;i<attachs.length;i++){ MultipartFile attach = attachs[i]; //判斷文件是否為空 if(!attach.isEmpty()){ //判斷是第幾個文件 if(i==0){ errorinfo = "uploadwkError"; }else if(i==1){ errorinfo = "uploadhdError"; } //獲取源文件名 String oldName= attach.getOriginalFilename(); //獲取源文件名后綴 String prefixName = FilenameUtils.getExtension(oldName); int fileSize = 500000; //判斷上傳大小不得超過500K if(attach.getSize()>fileSize){ session.setAttribute(errorinfo, "上傳文件不得大於500k"); flag = false; }else if(prefixName.equalsIgnoreCase("jpg") || prefixName.equalsIgnoreCase("png") || prefixName.equalsIgnoreCase("jpeg") || prefixName.equalsIgnoreCase("pneg")){ //判斷上傳格式 //定義新的文件名,當前系統時間+隨機數+固定后綴, //RandomUtils需要引入jar文件commons-lang.jar //String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"personer.jpg"; String fileName = System.currentTimeMillis()+"personer.jpg"; //創建新的文件,用於接收用戶上傳的文件流 File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //將上傳的文件保存 try { attach.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); session.setAttribute(errorinfo,"上傳失敗!"); flag = false; } //更新上傳的路徑 if(i==0){ wkpicpath = path + File.separator + fileName; }else if(i==1){ hdpicpath = path + File.separator + fileName; } }else{ session.setAttribute(errorinfo,"圖片格式不正確!"); flag = false; } } } //准備User if(flag){ user.setWkpicpath(wkpicpath); user.setHdpicpath(hdpicpath); user.setUserrole(1); //插入數據庫 if(userService.findAddUser(user)>0){ return "redirect:/index/user"; } } return "manager/user-add.jsp"; }