第一步:配置虚拟目录
在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
<Context docBase="D:\develop\upload\temp" path="/pic" reloadable="false"/>
开启Tomcat服务器,
访问http://localhost:8080/pic即可访问D:\develop\upload\temp下的图片。
此时, D:\develop\upload\temp==http://localhost:8080/pic可作为图片服务器第二部加入jar包
实现图片上传需要加入的jar包,如下图:
把两个jar包放到工程的lib文件夹中
第三步
1.1. 配置上传解析器
在springmvc.xml中配置文件上传解析器
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传大小 -->
<property name="maxUploadSize" value="5000000" />
</bean>
第四步修改jsp页面
设置表单可以进行文件上传,如下图:
<tr>
<td>商品图片</td>
<td>
<c:if test="${item.pic !=null}">
<img src="/pic/${item.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="pictureFile"/>
</td>
</tr>
1.1. 图片上传
在更新商品方法中添加图片上传逻辑
**
* 更新商品
*
* @param item
* @return
* @throws Exception
*/
@RequestMapping("updateItem")
public String updateItemById(Itemitem, MultipartFile pictureFile) throws Exception {
// 图片上传
// 设置图片名称,不能重复,可以使用uuid
String picName = UUID.randomUUID().toString();
// 获取文件名
String oriName = pictureFile.getOriginalFilename();
// 获取图片后缀
String extName = oriName.substring(oriName.lastIndexOf("."));
// 开始上传
pictureFile.transferTo(new File("C:/upload/image/" +picName + extName));
// 设置图片名到商品中
item.setPic(picName +extName);
// ---------------------------------------------
// 更新商品
this.itemService.updateItemById(item);
return "forward:/itemEdit.action";
}