使用MultipartResolver上传图片
话不多说直接上代码
controller
@RequestMapping("add.action")
public String addNewser(Model model, HttpSession session,MultipartFile upload, Newser newser, HttpServletRequest request) throws IOException {
newser.setNewseruser((User) session.getAttribute("success"));
//判断upload是否为空
if (!upload.isEmpty()) {
//1.getRealPath得到当前项目根目录
String uploadFilePath =request.getServletContext().getRealPath("/");
//2.自定义文件夹名称(照片的文件夹)
String folder = "/upload";
//3.合到一起1+2
String route = uploadFilePath+folder;
//4.使用UUID自定义吗、照片名称
String fileName = UUID.randomUUID().toString();
//5.获得原始名称
String oriName = upload.getOriginalFilename();
//6.获取后缀名
String suffix = oriName.substring(oriName.lastIndexOf("."));
//7.新建File对象
File file = new File(uploadFilePath + folder);
//8.判断文件夹是否存在如果不存在创建
if (!file.exists()) {
file.mkdirs();
}
//9.以文件后缀名判断是否符合图片文件格式
if (suffix.equalsIgnoreCase(".jpeg") || suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".png") || suffix.equalsIgnoreCase(".gif")) {
//10.文件重命名
String newName = fileName + suffix;
//11.传输
upload.transferTo(new File(route,newName));
//12.传入对象
newser.setPicPath(newName);
}
}
List<News> nt=newsService.queryAll();
model.addAttribute("nt",nt);
model.addAttribute("newser",newser);
newserService.saveorupdate(newser);
return "redirect:index.action";
}
xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10240000" />
<property name="maxInMemorySize" value="4096"/>
</bean>