可单例开发、典型的教科书式的mvc构架----springmvc----day02(四)
7.上传图片
7.1需求
在修改商品页面,添加上传商品图片功能。
7.2springmvc中对多部件类型解析
在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。
在springmvc.xml中配置multipart类型解析器。
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
7.3加入上传图片的jar
7.4创建图片虚拟目录存储图片
使用图形界面配置:
也可以直接修改tomcat配置:
在conf/server.xml文件,添加虚拟目录:
<Context docBase="F:\develop\upload\temp" path="/pic" reloadable="false"/>
注意:在图片虚拟目录中,一定将图片目录分级创建(提高I/O性能),一般我们采用按日期(年、月、日)进行分级创建。
7.5 上传图片代码
7.5.1页面
<td>商品图片</td>
<td><c:if test="${itemsCustom.pic !=null}">
<img src="/pic/${itemsCustom.pic}" width=100 height=100 />
<br />
</c:if> <input type="file" name="items_pic" /></td>
7.5.2controller方法
修改:商品修改controller方法:
// 商品提交修改
// 在需要校验的pojo前面添加@Validated,在需要校验的pojo的后面添加BindingResult bindingResult接收校验出错信息
// 注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)
// @ModelAttribute:指定pojo回显到页面的数据在request中的key
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model, HttpServletRequest request, Integer id,
@ModelAttribute("items") @Validated(value = { ValidGroup1.class }) ItemsCustom itemsCustom,
BindingResult bindingResult, MultipartFile items_pic// 接收商品图片
) throws Exception {
// 获取校验错误信息
if (bindingResult.hasErrors()) {
// 输出错误信息
List<ObjectError> allErrors = bindingResult.getAllErrors();
// 遍历错误信息
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", allErrors);
// 可以直接使用model将提交的pojo回显到页面
model.addAttribute("id", id);
model.addAttribute("items", itemsCustom);
System.out.println("数据出错,从新跳转到商品修改页面");
// 数据出错,从新跳转到商品修改页面
return "items/editItems";
}
// 上传图片
String originalFilename = items_pic.getOriginalFilename();
if (items_pic != null && originalFilename != null && originalFilename.length() > 0) {
// 存储图片的物理路径
String pic_path = "D:\\Java\\eclipse-workspace2\\springmvc_spring_mybatis_project\\temp";
// 原始名称
// 新的图片名称
String newFileName = UUID.randomUUID()
+ originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
// 新图片
File newFile = new File(pic_path + newFileName);
// 序列化
System.err.println(newFile.toString());
//
items_pic.transferTo(newFile);
// newFile.mkdir();
// 将新图片名称写到itemsCutom中
itemsCustom.setPic(newFileName);
// itemsCustom.setPic(originalFilename);
System.err.println(newFileName);
}
// 调用sevice根据商品id更新商品信息
Integer i = itemsService.updateItemsById(id, itemsCustom);
//
// ModelAndView modelAndView = queryItems();
// 重定向
// return "redirect:queryItems.action";
if (i != 0) {
// 请求转发·
return "success";
} else {
System.out.println("更新失败");
model.addAttribute("message", "数据更新失败");
return "error";
}
// return modelAndView;