文件下载

使用ResponseEntity实现下载文件的功能

  1. <mvc:view-controller path="/file" view-name="file"></mvc:view-controller>
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>测试文件上传和下载</title>
  6. </head>
  7. <body>
  8. <a th:href="@{/testDownload}">下载1.jpg</a>
  9. </body>
  10. </html>
  1. @Controller
  2. public class FileUpAndDownController {
  3. @RequestMapping("/testDownload")
  4. public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
  5. //获取整个工程对象
  6. ServletContext servletContext = session.getServletContext();
  7. //获取服务器中文件的真实路径
  8. String realPath = servletContext.getRealPath("/static/img/1.jpg");
  9. FileInputStream fileInputStream = new FileInputStream(realPath);
  10. //获取流中的所以字节数并创建字节数组
  11. byte[] bytes = new byte[fileInputStream.available()];
  12. //流读到字节数组中
  13. fileInputStream.read(bytes);
  14. //创建HttpHeaders
  15. MultiValueMap<String, String> headers = new HttpHeaders();
  16. //设置要下载方式以及下载文件的名字(默认文件名),只有文件名能改
  17. headers.add("Content-Disposition", "attachment;filename=1.jpg");
  18. //设置响应状态码
  19. HttpStatus statusCode = HttpStatus.OK;
  20. ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
  21. fileInputStream.close();
  22. return responseEntity;
  23. }
  24. }

文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype=”multipart/form-data”
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
a>添加依赖:

  1. <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
  2. <dependency>
  3. <groupId>commons-fileupload</groupId>
  4. <artifactId>commons-fileupload</artifactId>
  5. <version>1.3.1</version>
  6. </dependency>

b>在SpringMVC的配置文件中添加配置:

  1. <!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
  2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

c>控制器方法:

  1. @RequestMapping("/testUp")
  2. public String testUp(MultipartFile photo, HttpSession session) throws IOException {
  3. //获取上传的文件的文件名
  4. String fileName = photo.getOriginalFilename();
  5. //处理文件重名问题
  6. String hzName = fileName.substring(fileName.lastIndexOf("."));
  7. fileName = UUID.randomUUID().toString() + hzName;
  8. //获取服务器中photo目录的路径
  9. ServletContext servletContext = session.getServletContext();
  10. String photoPath = servletContext.getRealPath("photo");
  11. File file = new File(photoPath);
  12. if(!file.exists()){
  13. file.mkdir();
  14. }
  15. String finalPath = photoPath + File.separator + fileName;
  16. //实现上传功能
  17. photo.transferTo(new File(finalPath));
  18. return "success";
  19. }

d>视图:

  1. <form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
  2. 头像: <input type="file" name="photo"><br>
  3. <input type="submit" value="上传"><br>
  4. </form>