Springmvc3实现文件上传

阅读更多
Spring自己封装了文件上传功能,可以利用
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
MultipartFile multFile = multiRequest.getFile("imgFile");

需要在springmvc-servlet.xml里配置:


结合iframe实现局部刷新上传

代码:

1.JSP页面:

		
选择图片


2 controller后台:

/** 保存新增,@Valid标注spirng在绑定对象时自动为我们验证对象属性并存放errors在BindingResult  */
	@RequestMapping(value = "/save")
	public String create(ModelMap model,@Valid WzXxfbPdtp wzXxfbPdtp,HttpServletRequest request,HttpServletResponse response)throws Exception  {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
		MultipartFile multFile = multiRequest.getFile("imgFile");
		// 扩展名格式:
		String extName = "";
		String message = "";
		String newName = "";
		boolean flag = true;
		//取得上传的文件名
		String fileName = multFile.getOriginalFilename();
		if(fileName != null && !"".equals(fileName.trim())){
			//上传文件的大小
			long size = multFile.getSize();
			if(size > (1024*1024)){
				message = "只允许上传1M之内的图片";
				flag = false;
			}
			if (fileName.lastIndexOf(".") >= 0) {
				extName = fileName.substring(fileName.lastIndexOf("."));
			}
			//定义允许上传的文件类型
			List fileTypes = new ArrayList();
			fileTypes.add(".jpg");
			fileTypes.add(".jpeg");
			fileTypes.add(".gif");
			fileTypes.add(".png");
			if(!fileTypes.contains(extName.toLowerCase())){
				message = "只允许上传jpg,jpeg,gif,png格式的图片";
				flag = false;
			}
			String root=request.getSession().getServletContext().getRealPath("");
			String savePath = root+File.separator+"pdtpFolder"+File.separator;
			File f1 = new File(savePath);
			if (!f1.exists()) {
				f1.mkdirs();
			}
			if(flag){
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS");
				Calendar calendar = Calendar.getInstance();
				//以当前时间为文件名 格式如:2011-09-03-19-30-36047 
				newName = df.format(calendar.getTime());
				//newName = UUID.randomUUID().toString();
				File newFile = new File(savePath + newName + extName);
				try {
					multFile.transferTo(newFile);
				} catch (IllegalStateException e) {
					e.printStackTrace();
					flag = false;
				} catch (IOException e) {
					e.printStackTrace();
					flag = false;
				}
				//设置图片的相对地址
				wzXxfbPdtp.setTpdz("pdtpFolder/"+newName+extName);
				//图片原名称
				wzXxfbPdtp.setTpmc(fileName);
				//设置ID与新生成的图片名
				wzXxfbPdtp.setPkid(newName);
				wzXxfbPdtpManager.save(wzXxfbPdtp);
			}
		}
//		dwzCallback(model,CREATED_SUCCESS);
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.write("");
//		return LIST_ACTION;
		return null;
	}


3 springmvc-servlet.xml




	
    

	
	
	
	
		
		
			
		
	

    
	
	
    
    
    	
		
		
    	
		
			
				
				
			
		
		
		
		
			
				
			    
			        
			        
			        
			    
			
		
		
			
				
				
				
				
			
		
    
    
    
    
        
            
            
        
    
        




Springmvc3实现文件上传_第1张图片


###############################################################
使用DiskFileItemFactory 及ServletFileUpload 组件进行上传
需要注意的是:所有的Form表单数据不再会自动绑定赋值,需要手动去设置值,还有就是不需要在springmvc-servlet.xml里配置:

后台处理类:

@Controller
@RequestMapping("/wzxxfbpdtp")
public class WzXxfbPdtpController extends BaseRestSpringController{
//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = ""; 
	private WzXxfbPdtpManager wzXxfbPdtpManager;
	private final String LIST_ACTION = "redirect:/wzxxfbpdtp/manager";
	/** 
	 * 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写
	 **/
	public void setWzXxfbPdtpManager(WzXxfbPdtpManager manager) {
		this.wzXxfbPdtpManager = manager;
	}
		String extName = "";
		String message = "";
		boolean flag = true;
		Iterator it = fileList.iterator();
		while (it.hasNext()) {
			FileItem item = it.next();
			//给取表单域的值,赋给wzXxfbPdtp对象
			setFormFields(wzXxfbPdtp, item);
			// 如果是文件类型字段
			if (!item.isFormField()) {
				name = item.getName();
				long size = item.getSize();
				if(size>(1024*1024)){
					message="文件"+item.getName()+"大超过了1M,上传失败!";
					json.put("statusCode", "300");
					json.put("message", message);
					flag = false;
					break;
				}
				// 扩展名格式:
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				// 定义允许上传的文件类型
				List fileTypes = new ArrayList();
				fileTypes.add(".jpg");
				fileTypes.add(".jpeg");
				fileTypes.add(".gif");
				fileTypes.add(".png");
				if(!fileTypes.contains(extName.toLowerCase())){
					message = "只允许上传jpg,jpeg,gif,png格式的图片";
					json.put("statusCode", "300");
					json.put("message", message);
					flag = false;
					break;
				}
				if(flag) {
					DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS");
					Calendar calendar2 = Calendar.getInstance();
					//以当前时间为文件名 格式如:2011-09-03-19-30-36047 
					newName = df2.format(calendar2.getTime());
					File newFile = new File(savePath+"/"+folderName+"/" + newName + extName);
					item.write(newFile);
					//设置图片的相对地址
					wzXxfbPdtp.setTpdz(rootFile.getName()+"/"+folderName+"/"+newName+extName);
					//图片原名称
					wzXxfbPdtp.setTpmc(name);
				} 
			}
		}
		if(flag){
			wzXxfbPdtpManager.save(wzXxfbPdtp);
			json.put("navTabId", "BM01040000");
			json.put("statusCode", "200");
			json.put("callbackType", "closeCurrent");
			json.put("message", CREATED_SUCCESS);
		}
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.write(json.toString());
		out.flush();
		out.close();
		return null;
	}
/*
	 * 取得Form表单各文本域的值,赋给wzXxfbPdtp对象
	 */
	private void setFormFields(WzXxfbPdtp wzXxfbPdtp, FileItem item) throws UnsupportedEncodingException {
		if(item.isFormField()){
			String field = item.getFieldName();
			String temp;
			if(field.equals("zzdm")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setZzdm(temp);
			}
			if(field.equals("zzjc")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setZzjc(temp);
			}
			if(field.equals("bmdm")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setBmdm(temp);
			}
			if(field.equals("bmjc")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setBmjc(temp);
			}
			if(field.equals("tpbt")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setTpbt(temp);
			}
			if(field.equals("tplj")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setTplj(temp);
			}
			if(field.equals("kd")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setKd(Integer.parseInt(temp));
			}
			if(field.equals("gd")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setGd(Integer.parseInt(temp));
			}
			if(field.equals("sfpd")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setSfpd(temp);
			}
		}
	}
	
//删除本地图片文件
	private void deleteLocalFile(HttpServletRequest request, WzXxfbPdtp pdtp) {
		String	path = pdtp.getTpdz();
		String	root = request.getSession().getServletContext().getRealPath("");
		File rootFile =  new File(root);
		//得到图片存放的完整路径

		String savePath = rootFile.getParent()+ConstantUtils.getFilePath()+"/"+path;
		File f1 = new File(savePath);
		if(f1.exists()){
			f1.delete();
		}
	}


页面显示跟上图一样
  • Springmvc3实现文件上传_第2张图片
  • 大小: 64.7 KB
  • 查看图片附件

你可能感兴趣的:(springmvc,json,servlet)