springMVC图片文件上传功能的实现

  1. 在工程依赖库下添加文件上传jar包

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

2.jsp页面设置form表单属性enctype

在表单中上传图片时,需要在form的属性设置中添加enctype="multipart/form-data"。

[html] view plain copy

表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作. enctype="multipart/form-data"是上传二进制数据;form里面的input的值以2进制的方式传过去。

  1. springMVC.xml添加multipart类型解析器

在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析,需要在springmvc.xml中配置multipart类型解析器。

[html] view plain copy





5242880

4.创建图片虚拟目录,以存放图片

eclipse IDE 通过界面进行配置:servers -->Tomcat v8.0 Server at localhost--> 双击,选择-->add external web modules.

在图片虚拟目录中,一定将图片目录分级创建(提高i/o性能),一般我们采用按日期(年、月、日)进行分级创建。

  1. jsp 页面,设置图片显示的位置和大小。

[html] view plain copy


商品图片

<c:if test="${itemsCustom.pic !=null}">



</c:if>


lt;/tr>

  1. Controller 类方法中写相应的方法

<1, 方法的参数中添加MultipartFile items_pic行参 这个跟页面的图片的参数名字是一致的;

<2, 为了避免文件名称相同而冲突,使用UUID.randomUUID()产生一个随机的数值作为名称;

❤️. 将图片数据写入磁盘:items_pic.transferTo(newFile);

<4. 更新itemsCustom中属性pic的值itemsCustom.setPic(newFileName);
[java] view plain copy

//在需要校验的poJo类前加 @Validated, 后面加BindingResult bindingResult 存放出错信息。
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,
HttpServletRequest request,Integer id,
@Validated ItemsCustom itemsCustom,
BindingResult bindingResult,
MultipartFile items_pic)throws Exception {

if(bindingResult.hasErrors()){
List allErrors = bindingResult.getAllErrors();
for(ObjectError objectError :allErrors){
System.out.println(objectError.getDefaultMessage());
}

model.addAttribute("allErrors", allErrors);
model.addAttribute("itemsCustom", itemsCustom);
return "items/editItems";
}

//原始名称
String originalFilename = items_pic.getOriginalFilename();
//上传图片
if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){
//存储图片的物理路径
String pic_path = "C:\Users\Administrator.MICROSO-U8JSS8B\Desktop\java_code\picture\";
//新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//新图片
File newFile = new File(pic_path+newFileName);
//将内存中的数据写入磁盘
items_pic.transferTo(newFile);
//将新图片名称写到itemsCustom中
itemsCustom.setPic(newFileName);

}
itemsService.updateItems(id, itemsCustom);

// return "success";
return "forward:queryItems.action";
}

7.测试效果

参考:http://zkliqiang.iteye.com/blog/779285

posted @ 2016-12-06 12:54  Hosens  阅读(9285)  评论(0)    收藏  举报