SpringMVC的文件上传与下载
1. 单文件上传
配置jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <form action="/file/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> 作者:<input type="text" name="author"/> <input type="submit" value="提交"> </form> </body> </html>
配置文件上传的解析器
在WEB-INF里创建upload文件夹
效果展示
<!--CommonsMultipartResolver文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--编码--> <property name="defaultEncoding" value="UTF-8"/> <property name="maxInMemorySize" value="500000"/> </bean>
2. 多文件上传
- 编写jsp页面
Form表单加上enctype="multipart/form-data"
input 属性的name值必须保持一致
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>多文件上传</title> </head> <body> <form action="/file/fileUploads" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFiles"/> <input type="file" name="uploadFiles"/> <input type="file" name="uploadFiles"/> 作者:<input type="text" name="author"/> <input type="submit" value="提交"> </form> </body> </html>
@RequestMapping("/fileUploads") public String fileMothers(HttpSession session, @RequestParam MultipartFile[] uploadFiles,String author) throws IOException { System.out.println("作者:"+author); System.out.println(uploadFiles); /*如何处理文件*/ for (MultipartFile file:uploadFiles) { if (!file.isEmpty()) { //获取文件名称 String fileName = file.getOriginalFilename(); //获取需要上传的路径 String realPath = session.getServletContext().getRealPath("/WEB-INF/upload"); //创建文件对象 File uploadfile = new File(realPath + "\\" + fileName); //如何上传文件 file.transferTo(uploadfile); } } return "main"; }
实现handler文件
@RequestMapping("/springmvc") @Controller public class SpringMVCTest { /** *来一波上传文件 ,用@RequestParam注解来指定表单上的file为MultipartFile */ @RequestMapping("/fileUpload") public void fileUpload(@RequestParam("file") MultipartFile file){ // 判断文件是否为空 if (!file.isEmpty()) { try { // 文件保存路径 String filePath = "E:\\MySQL\\springmvc_test\\" + file.getOriginalFilename(); // 转存文件 System.out.println(filePath); file.transferTo(new File(filePath)); File uploadDest = new File(filePath); String[] fileNames = uploadDest.list(); for (int i = 0; i < fileNames.length; i++) { //打印出文件名 System.out.println(fileNames[i]); } } catch (Exception e) { e.printStackTrace(); } } } }
注意:我上面没有返回字符串或者是ModelAndView。。虽然能上传文件,但是跳转页面会是404,如下图:
这里进行修改
/** *来一波上传文件 ,用@RequestParam注解来指定表单上的file为MultipartFile */ @RequestMapping("/fileUpload") public String fileUpload(@RequestParam("file") MultipartFile file){ // 判断文件是否为空 if (!file.isEmpty()) { try { // 文件保存路径 String filePath = "E:\\MySQL\\springmvc_test\\" + file.getOriginalFilename(); // 转存文件 System.out.println(filePath); file.transferTo(new File(filePath)); File uploadDest = new File(filePath); String[] fileNames = uploadDest.list(); for (int i = 0; i < fileNames.length; i++) { //打印出文件名 System.out.println(fileNames[i]); } } catch (Exception e) { e.printStackTrace(); } } // 重定向 return SUCCESS; }
3.文件下载
修改index.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=UYF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/fileUpload" method="post" enctype="multipart/form-data"> choose file:<input type="file" name="file"> <input type="submit" value="submit"> </form> <br><br> <a href="springmvc/testResponseEntity">Test ResponseEntity</a </body> </html>
在Controller中添加对应 handler:
@RequestMapping("/testResponseEntity") public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException { byte[] body =null; ServletContext servletContext = session.getServletContext(); InputStream in = servletContext.getResourceAsStream("/files/abc.txt"); body = new byte[in.available()]; in.read(body); HttpHeaders headers = new HttpHeaders(); //添加头部信息 headers.add("Content-Disposition", "attachment;filename=abc.txt"); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode); return response; }
点击超链接,左下角看到