servlet及Springmvc文件上传

request.setCharacterEncoding("utf-8");
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(dfif);
		
		String id=request.getParameter("id");
		List<FileItem> list;
		String idpathString="";
		try {
			list = fileUpload.parseRequest(request);
			FileItem fileItem = list.get(0);
			String name = fileItem.getName();
			String savepath = this.getServletContext().getRealPath("/WEB-INF/upload");
	
			String filename = UUID.randomUUID() + "_" + name;
            File file = new File(savepath, filename);
			// 保存文件
            idpathString="/WEB-INF/upload/"+filename;
			fileItem.write(file);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
@RequestMapping(value = "/useraddsave.html", method = RequestMethod.POST)
public String useradd(User user, HttpSession session, HttpServletRequest request,
@RequestParam(value = "a_idPicPath", required = false) MultipartFile file) throws Exception {
		String idPicPath = " ";

		// 加入上传 判断文件是否为空
		if (!file.isEmpty()) {
			String path = request.getSession().getServletContext()
.getRealPath("statics" + File.separator + "upload");
			String oldName = file.getOriginalFilename();// 原文件的文件名
			String prefix = FilenameUtils.getExtension(oldName);// 获取文件尾椎名
			if (file.getSize() > 500000) {
				request.setAttribute("uploaderror", "文件大小不能超过500k");
				return "useradd";
			} 
else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")) {
				// 文件名尾椎 系统时间+随机数+固定的文件
				String fileName = System.currentTimeMillis() + 
RandomUtils.nextInt(10000) + "_pic.jpg";
				File tatangFile = new File(path, fileName);
				if (!tatangFile.exists()) {
					tatangFile.mkdirs();
				}
				// 保存到数据库当中
				try {
					file.transferTo(tatangFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("uploaderror", "上传失败!");
				}
				// 上传成功
				idPicPath = path + File.separator + fileName;
			} else {
				request.setAttribute("uploaderror", "上传图片格式不对");
				return "useradd";
			}
		}
		// 如果保存失败了
		user.setIdPicPath(idPicPath);
		user.setCreatedBy(((User) (session.getAttribute(Constants.USER_SESSION))).getId());
		user.setCreationDate(new Date());
		if (uService.useradd(user) > 0) {

			return "redirect:/user/userList.html";
		}
		return "useradd";

	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值