在pom.xml中加入
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </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>