eclispe中配置虚拟路径配置
上图的真实路径是D:\images\2.jpg
jar包
commons-fileupload.jar和commons-io.jar
springmvc.xml中的配置
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
jsp中的代码
<tr>
<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="picture"/>
</td>
</tr>
controller中的代码
public String editItemSubmit(Model model,Integer id,
@ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
//上传图片
MultipartFile picture
)throws Exception{
//进行图片上传
if(picture!=null && picture.getOriginalFilename()!=null && picture.getOriginalFilename().length()>0){
//图片上传成功后,将图片的地址写到数据库
String filePath = "D:\\images\\";
//上传文件原始名称
String originalFilename = picture.getOriginalFilename();
//新的图片名称
String newFileName = UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));
//新文件
File file = new java.io.File(filePath+newFileName);
//将内存中的文件写入磁盘
picture.transferTo(file);
//图片上传成功,将新图片地址写入数据库
itemsCustom.setPic(newFileName);
}
//调用service接口更新商品信息
itemsService.updateItems(id, itemsCustom);
//转发
return "forward:queryItems.action";
}