在pom.xml中加入
<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>
2.在spring的配置文件中加入
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>
3.前台
<body>
<form action="${basePath}file/upload" method="post" enctype="multipart/form-data">
<label>用户名:</label><input type="text" name="name"/><br/>
<label>密 码:</label><input type="password" name="password"/><br/>
<label>头 像1</label><input type="file" name="file"/><br/>
<label>头 像2</label><input type="file" name="file"/><br/>
<input type="submit" value="提 交"/>
</form>
</body>
4.后台
@RequestMapping("addSchoolHonor")
public String addSchoolHonor(Model model, @RequestParam(value = "file", required = false) MultipartFile[] file,TbResource tbResource) throws IllegalStateException, IOException {
TbCategory item = categoryService.selectCaName(tbResource.getCaName());
if (!item.equals(null)) {
TbResource tb = new TbResource();
tb.setCaId(item.getCaId());
tb.setCaName(tbResource.getCaName());
if(!tbResource.getCaName().equals("校园风光")) {
tb.setReContent(tbResource.getReContent());
}
for (MultipartFile mf : file) {
if (!mf.isEmpty()) {
String path =
session.getServletContext().getRealPath("/static/uploadimg");
//‘’/static/uploadimg‘’是自己webContent下的包
String fileName = mf.getOriginalFilename();
fileName = UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
// uuid+文件扩展名避免重名,中文名等问题
File uploadFile = new File(path, fileName);
mf.transferTo(uploadFile);
tb.setReTitle(fileName);
resourceService.insert(tb);
}
}
model.addAttribute("message", "添加成功");
} else {
model.addAttribute("message", "不存在该类别,添加失败");
}
return "admin/general/addschoolhonor";
}
5.返回前台显示时
<tr th:each="general,generalStart:${pagemsg.lists}">
<td><img alt="无图片" width="100px;" height="80px;" th:src="@{/static/uploadimg/{picture}(picture=${general.reTitle})}" /></td>
<td th:if="${sign}=='1'"><a th:href="@{/general/deleteScenery?(id=${general.reId})}" onclick="return confirm('确定要删除吗')">Delete</a></td></tr>