1. 程式人生 > >Spring MVC實現多檔案上傳

Spring MVC實現多檔案上傳

1、修改POJO和DAO實現類 

public class User{
    //......其他屬性省略
    private String idPicPath;//證件照路徑
    private String workPicPath;//工作證照片路徑
    // ......getter和setter 方法省略
}

 public int add(Connection connection, User user) throws Exception {         PreparedStatement pstm = null;         int updateRows = 0;         if(null != connection){             String sql = "insert into smbms_user (userCode,userName,userPassword," +                     "userRole,gender,birthday,phone,address,creationDate,createdBy,idPicPath,workPicPath

) " +                     "values(?,?,?,?,?,?,?,?,?,?,?,?)";             Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),                             user.getUserRole(),user.getGender(),user.getBirthday(),                             user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy(),user.getIdPicPath(),user.getWorkPicPath()
};             updateRows = BaseDao.executeUpdate(connection, pstm, sql, params);             BaseDao.closeAll(null, pstm, null);         }         return updateRows;     }

 2、改造檔案上傳表單頁

 <div>         <input type="hidden" id="errorinfo" value="${uploadFileError }">         <label for="a_idpicpath">證件照:</label>         <input type="file" name="attachs"

id="a_idpicpath" />          <font color="red"></font> </div> <div>         <input type="hidden" id="errorinfo_wp" value="${uploadFileError }">         <label for="a_workPicPath">工作證照片:</label>         <input type="file" name="attachs" id="a_workPicPath" />      <font color="red"></font>  </div>

 注意:Spring MVC處理多檔案上傳:表單頁面增加file標籤即可,但是需要注意上傳檔案的元件名需要一致,將來會以陣列的形式傳遞給控制器的處理方法。

3、改造控制器

@RequestMapping(value="/addsave.html",method=RequestMethod.POST)
	public String addUserSave(User user, HttpSession session,
							  HttpServletRequest request,
							  @RequestParam(value="attachs",required=false) MultipartFile [] attachs){
		String idPicPath=null;
		String workPicPath=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="uploadFileError";
			}else if(i==1){
				errorInfo="uploadWpError";
			}
			String oldFileName=attach.getOriginalFilename();//原檔名
			String prefix=FilenameUtils.getExtension(oldFileName);//原檔案字尾
			int filesize=500000;
			if(attach.getSize()>filesize){
				request.setAttribute("uploadFileError", "上傳檔案不得超過 500KB");
				return "useradd";
			}else if(prefix.equalsIgnoreCase("jpg") 
					|| prefix.equalsIgnoreCase("png")  
					|| prefix.equalsIgnoreCase("jpeg")  
					|| prefix.equalsIgnoreCase("pneg")){//上傳圖片格式不正確
				String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
				File targetFile=new File(path, fileName);
				if(!targetFile.exists()){
					targetFile.mkdirs();
				}
				//儲存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("uploadFileError", " * 上傳失敗!");
					flag=false;
				} 
				if(i==0){
					idPicPath=path+File.separator+fileName;
				}else if(i==1){
					workPicPath=path+File.separator+fileName;
				}
			}else{
				request.setAttribute("uploadFileError", " * 上傳圖片格式不正確!");
				flag=false;
			}
		  }
	   }
		if(flag){
			user.setCreatedBy( ((User)session.getAttribute(Constants.USER_SESSION)).getId());//建立者
			user.setCreationDate(new Date());//建立時間
			user.setIdPicPath(idPicPath);
			user.setWorkPicPath(workPicPath);
			if(userService.add(user)){
				return "redirect:/user/userlist.html";
			}
		}
		return "useradd";
	}

注意:多檔案上傳,也可以採用單獨入參,控制器處理方法如下:

 public String addUserSave(User user,               HttpSession session,               HttpServletRequest request,               @RequestParam(value="a_idpicPath",required=false) MultipartFile idPicFile,               @RequestParam(value="a_workPicPath",required=false) MultipartFile workPicFile){         // ......方法體省略(分別進行兩個檔案的上傳操作和資料庫相應欄位的更新)     }

還需要修改頁面(useradd.jsp)file標籤的name屬性,如下所示:

<input type="file" name="a_idpicPath"  id="a_idpicpath" />  <input type="file" name="a_workPicPath"  id="a_workPicPath" />