1.在springmvc中配置
<bean id="multipartResolver" class=" org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
2.设置表单属性(注意!:file按钮的name不能和数据库表中文件路径字段名重复)
enctype="multipart/form-data"
3.controller层写法
@RequestMapping("updateOrAdd.do")
public String toUpdateStand(Standard standard,MultipartFile picture) throws Exception{
//生成文件名
String picName = UUID.randomUUID().toString().replaceAll("-", "");
//获取文件名
String oriName = picture.getOriginalFilename();
//获得扩展名
String extName = FilenameUtils.getExtension(oriName);
try {
picture.transferTo(new File("F:\\upload\\image\\"+picName+"."+extName));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
standard.setPictureFile(picName+"."+extName);
if(standard.getId()!=null){standardService.toUpdateStand(standard);}else{standardService.addStand(standard);}
return "redirect:getStdandList.do";
}
原文:https://www.cnblogs.com/ZhangHaiBK/p/8988703.html