配置虚拟目录
配置解析器
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>```
jar包
图片上传
controller:
//商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Items items, MultipartFile pictureFile)throws Exception{
//原始文件名称
String pictureFile_name = pictureFile.getOriginalFilename();
//新文件名称
String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
//上传图片
File uploadPic = new java.io.File("F:/develop/upload/temp/"+newFileName);
if(!uploadPic.exists()){
uploadPic.mkdirs();
}
//向磁盘写文件
pictureFile.transferTo(uploadPic);```
页面:
form添加enctype="multipart/form-data":
<form id="itemForm"
action="${pageContext.request.contextPath }/item/editItemSubmit.action"
method="post" enctype="multipart/form-data">
<input type="hidden" name="pic" value="${item.pic }" />
file的name与controller形参一致:
<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>```
网友评论