前端
<p>上传多个照片并保存</p>
<form action="${pageContext.request.contextPath}/addImg" method="post" enctype="multipart/form-data">
<table >
<tr>
<td>上传图片:</td>
<td><input type="file" name="file" /></td>
<td><input type="file" name="file" /></td>
<td><input type="file" name="file" /></td>
</tr>
</table>
<button type="submit" >保存</button>
</form>
效果
controller
@RequestMapping(value = "/addImg")
private String addImg(@RequestParam(value = "file", required = false) CommonsMultipartFile[] file,
HttpServletRequest request,Model model) throws Exception {
//定义序号
int count = 1;
for (CommonsMultipartFile mf : file) {
System.out.println(mf.toString());
if (!mf.isEmpty()) {
// 使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
// 获取文件的扩展名
String ext = FilenameUtils.getExtension(mf
.getOriginalFilename());
// 设置图片上传路径
String url = request.getSession().getServletContext()
.getRealPath("/upload");
System.out.println(url);
// 以绝对路径保存重名命后的图片
mf.transferTo(new File(url + "/" + name + "." + ext));
// 把图片存储路径保存到数据库
String path = "upload/" + name + "." + ext;
if(count==1){
imginfo.AddImge(path);
}else if(count==2){
imginfo.AddImge(path);
}else if(count==3){
imginfo.AddImge(path);
}
}
count++;
}
List<Imginfo> imginfoList = imginfo.GetAllAddress();
System.out.println(imginfoList);
Object[] objects = imginfoList.toArray();
System.out.println(objects);
model.addAttribute("img",objects);
return "hello";
}
maven包
<!-- 文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
xml配置
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
展示页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script type="text/javascript" src="${pageContext.request.contextPath}./static/js/jquery.js"></script>
<%-- 记得引入jquery --%>
<p>多个照片</p>
<c:forEach var="b" items="${img}">
<img src="${b.imgAddress}">
</c:forEach>
效果
pojo、dao和sql就不写了!!!