SpringMVC实现多文件上传
人气:01)创建工程并导入JAR包
2)创建多文件选择页面
在 WebContent 目录下创建 JSP 页面 multiFiles.jsp,在该页面中使用表单上传多个文件,具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath }/multifile" method="post" enctype="multipart/form-data"> 选择文件1:<input type="file" name="myfile"><br> 文件描述1:<input type="text" name="description"><br /> 选择文件2:<input type="file" name="myfile"><br> 文件描述2:<input type="text" name="description"><br /> 选择文件3:<input type="file" name="myfile"><br> 文件描述3:<input type="text" name="description"><br /> <input type="submit" value="提交"> </form> </body> </html>
3)创建POJO类
package pers.zhang.pojo; import java.util.List; import org.springframework.web.multipart.MultipartFile; public class MultiFileDomain { private List<String> description; private List<MultipartFile> myfile; public List<String> getDescription() { return description; } public void setDescription(List<String> description) { this.description = description; } public List<MultipartFile> getMyfile() { return myfile; } public void setMyfile(List<MultipartFile> myfile) { this.myfile = myfile; } }
4)创建多文件上传处理方法
/** * 多文件上传 */ @RequestMapping("/multifile") public String multiFileUpload(@ModelAttribute MultiFileDomain multiFileDomain,HttpServletRequest request) { String realpath = request.getServletContext().getRealPath("uploadfiles"); File targetDir = new File(realpath); if (!targetDir.exists()) { targetDir.mkdirs(); } List<MultipartFile> files = multiFileDomain.getMyFile(); for (int i = 0; i < files.size(); i++) { MultipartFile file = files.get(i); String fileName = file.getOriginalFilename(); File targetFile = new File(realpath, fileName); // 上传 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } } logger.info("成功"); return "showMulti"; }
5)创建成功显示页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table> <tr> <td>详情</td> <td>文件名</td> </tr> <!-- 同时取两个数组的元素 --> <c:forEach items="${multiFileDomain.description}" var="description" varStatus="loop"> <tr> <td>${description}</td> <td>${multiFileDomain.myfile[loop.count-1].originalFilename}</td> </tr> </c:forEach> <!-- fileDomain.getMyfile().getOriginalFilename() --> </table> </body> </html>
6)测试文件上传
您可能感兴趣的文章:
加载全部内容