天天看点

springmvc上传多张图片

在pom.xml中加入

  1. <dependency>  
  2.     <groupId>commons-fileupload</groupId>  
  3.     <artifactId>commons-fileupload</artifactId>  
  4.     <version>1.3.1</version>  
  5. </dependency>  
  6.     <groupId>commons-io</groupId>  
  7.     <artifactId>commons-io</artifactId>  
  8.     <version>2.4</version>  
  9. </dependency>  

2.在spring的配置文件中加入

  1. <!-- 上传文件 -->  
  2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  3.     <property name="defaultEncoding" value="utf-8"/>  
  4.     <!-- 最大内存大小 -->  
  5.     <property name="maxInMemorySize" value="10240"/>  
  6.     <!-- 最大文件大小,-1为不限制大小 -->  
  7.     <property name="maxUploadSize" value="-1"/>  
  8. </bean>  

3.前台

  1. <body>  
  2. <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">  
  3.     <label>用户名:</label><input type="text" name="name"/><br/>  
  4.     <label>密 码:</label><input type="password" name="password"/><br/>  
  5.     <label>头 像1</label><input type="file" name="file"/><br/>  
  6.     <label>头 像2</label><input type="file" name="file"/><br/>  
  7.     <input type="submit" value="提  交"/>  
  8. </form>  
  9. </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>