spring-mvc的文件上传

一个新增用户的操作  附加文件上传

	@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
	public String savaUser(User user, HttpSession session,
			@RequestParam(value="idPicPath2" ,required=false) MultipartFile[] attach,HttpServletRequest request) {
		String idPicPath=null;		//保存第一个文件名
		String workPath=null;		//第二个文件名
		String relPath="statics"+File.separator+"uploadfiles";		//取文件的相对路径  从/statics开始
		//循环传入的文件进行上传
		for (int i = 0; i < attach.length; i++) {
			if(attach[i]!=null){
				String path=request.getSession().getServletContext().getRealPath(relPath);//文件全名  
				String oldFileName=attach[i].getOriginalFilename();		//源文件名
				String prefix=FilenameUtils.getExtension(oldFileName);		//获得文件后缀
				int fileSize=500000;									//上传文件的最大字节数
				if(attach[i].getSize()>fileSize){
					//文件太大
					request.setAttribute("uploadFileError", "文件太大");
					return "useradd";
				}else if(prefix.equalsIgnoreCase("jpg") ||			//判断文件格式
						prefix.equalsIgnoreCase("png")){
					//修改文件名称  系统时间的毫秒数+生成一个随机数+统一后缀
					String fileName=System.currentTimeMillis()+RandomUtils.nextInt(10000)+"_Personal.jpg";
					logger.debug("new fileName======="+attach[i].getName());
					//创建文件流 判断文件是否存在,不存在创建文件
					File targetFile=new File(path,fileName); 
					if(!targetFile.exists()){
						targetFile.mkdirs();
					}
					//保存
					try {
						//将传入的数据流写入到目标文件
						attach[i].transferTo(targetFile);
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						request.setAttribute("uploadFileError", "上传失败");
						return "useradd";
					}
					if(i==0)
						idPicPath=relPath+File.separator+fileName;
					else if(i==1)
						workPath=relPath+File.separator+fileName;
				}else{
					request.setAttribute("uploadFileError", "文件格式不正确");
					return "useradd";
				}
			}
		}
		//判断文件是否为空
		System.out.println(workPath);
		System.out.println(idPicPath);
		user.setIdPicPath(idPicPath);
		user.setWorkPath(workPath);
		user.setCreatedBy(((User) (session.getAttribute(Constants.USER_SESSION))).getId());
		user.setCreationDate(new Date());
		if (userService.add(user)) {
			System.out.println("增加成功");
			return "redirect:/user/userList";
		}
		return "userAdd";
	}

控制台输出两个文件和上传后的文件名成 




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值