前台代码
注:/pic tomcat访问本地磁盘路径 (=x:xxx)
<tr>
<td>商品图片</td>
<td>
<c:if test="${对象类型.pic !=null}">
<img src="/pic/${对象类型.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="pictureFile"/>
</td>
</tr>
<td>商品图片</td>
<td>
<c:if test="${对象类型.pic !=null}">
<img src="/pic/${对象类型.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="pictureFile"/>
</td>
</tr>
后台代码
注:MultipartFile 的实现类需要在springMvc配置
@RequestMapping("/item/updateItem.action")
public ModelAndView updateItem(Items item,MultipartFile pictureFile) throws Exception{
//String name = pictureFile.getName(); 得到input name值
String name = pictureFile.getOriginalFilename(); 得到上传文件的名字.
String ext = FilenameUtils.getExtension(name); 得到文件类型
String fileName=UUID.randomUUID()+"."+ext;
File targetFile = new File("F:/tomcat_picture/", fileName);
pictureFile.transferTo(targetFile);
item.setPic(fileName);
itemService.updateItem(item);
ModelAndView mav=new ModelAndView();
mav.setViewName("success");
return mav;
}
SpingMvc配置文件
<!-- 上传文件的实体类,id一定是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>