欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

springmvc文件上传和下载

时间:2023-07-06
一、文件上传

SpringMVC为文件上传提供了直接支持,这种支持是通过即插即用MultipartResolver实现的。

Spring中有一个MultipartResolver实现类:CommonsMultipartResolver

Spring上下文中默认没有装配MultipartResolver,因此默认情况下不能处理文件上传工作。想要使用上传功能,需要在上下文中装配MultipartResolver。

1.1、添加依赖

commons-fileupload commons-fileupload 1.3.1

1.2、springmvc.xml中配置MultipartResolver

1.3、页面表单及上传文件夹

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 文件操作

1.4、上传控制类

@Controller@RequestMapping("file")public class FileController { @RequestMapping("upload") public String upload(@RequestParam("myFile")MultipartFile myFile, HttpServletRequest request){ String originalFilename = myFile.getOriginalFilename(); String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".")); System.out.println(fileName); String realPath=request.getServletContext().getRealPath("/uploadFile")+"/"; try { myFile.transferTo(new File(realPath+fileName)); System.out.println("上传成功"+realPath+fileName); } catch (IOException e) { e.printStackTrace(); } return "ok"; } @RequestMapping("hello") public String hello(){ return "/jsp/fileHandle"; } }

1.5、限制文件类型

1、添加过滤器 FileInterceptor

public class FileInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { boolean result=true; //判断是否是文件上传请求 if(request instanceof MultipartHttpServletRequest){ //获取文件对象map MultipartHttpServletRequest multipartRequest= (MultipartHttpServletRequest) request; Map fileMap = multipartRequest.getFileMap(); //遍历map集合中的file for(Map.Entry map: fileMap.entrySet()){ //获取文件名中的后缀 MultipartFile file = map.getValue(); String originalFilename = file.getOriginalFilename(); String suffix=originalFilename.substring(originalFilename.lastIndexOf(".")); //判断后缀是否满足要求 if(!suffix.equalsIgnoreCase(".png")&&!suffix.equalsIgnoreCase(".jpg") &&!suffix.equalsIgnoreCase(".gif")&&!suffix.equalsIgnoreCase(".jpeg")){ request.getRequestDispatcher("/jsp/fileError.jsp").forward(request,response); result=false; } } } return result; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}

2、配置过滤器到springmvc.xml

3、添加上传错误页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %> Title文件类型上传错误,文件必须是.png、.jpg、.jpeg、.gif格式

二、文件下载 2.1、下载前端页面


2.2、下载文件控制类

@RequestMapping("download") public ResponseEntity download(HttpServletRequest request) throws IOException { //指定文件路径 String fileName="a6a9ac28393742358b33582d69ee497e.jpg"; String filePath=request.getServletContext().getRealPath("/uploadFile")+"/"+fileName; File file=new File(filePath); //创建响应的头信息 HttpHeaders headers=new HttpHeaders(); //标记以流的形式作出响应 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //以附件形式响应给用户 headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8")); ResponseEntity resp=new ResponseEntity<> (FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED); return resp; }

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。