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";
}