• SpringMVC实现文件的上传和下载


    1. 文件的下载

    下面代码只需要设置服务器文件名(getRealPath("/static/img/1.jpg"))和下载到本地的文件名("attachment;filename=1.jpg")

    关于ServletContext.getRealPath()

    ServletContext.getRealPath("") 获取到的是项目部署到服务器后的项目根路径。

    ServletContext.getRealPath("文件名或文件夹名") 获取到的是项目部署到服务器后某文件或文件夹的路径。

    String photoPath1 = servletContext.getRealPath("");

    F:\JavaProject\SpringMVC\springMVC-demo04\target\springMVC-demo04\

    String photoPath = servletContext.getRealPath("photo");

    F:\JavaProject\SpringMVC\springMVC-demo04\target\springMVC-demo04\photo

    1. @RequestMapping("/testDown")
    2. public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
    3. //获取ServletContext对象
    4. ServletContext servletContext = session.getServletContext();
    5. //获取服务器中文件的真实路径
    6. String realPath = servletContext.getRealPath("/static/img/1.jpg");
    7. //创建输入流
    8. InputStream is = new FileInputStream(realPath);
    9. //创建字节数组
    10. //is.available()获取输入流的文件全部的字节
    11. byte[] bytes = new byte[is.available()];
    12. //将流读到字节数组中
    13. is.read(bytes);
    14. //创建HttpHeaders对象设置响应头信息
    15. MultiValueMap headers = new HttpHeaders();
    16. //设置要下载方式以及下载文件的名字
    17. headers.add("Content-Disposition", "attachment;filename=1.jpg");
    18. //设置响应状态码
    19. HttpStatus statusCode = HttpStatus.OK;
    20. //创建ResponseEntity对象
    21. //bytes 响应体
    22. //headers响应头
    23. ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    24. //关闭输入流
    25. is.close();
    26. return responseEntity;
    27. }

    2. 文件的上传

    文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”

    SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息

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

    1. 添加依赖 在SpringMVC的配置文件中添加配置:

    1. <dependency>
    2. <groupId>commons-fileuploadgroupId>
    3. <artifactId>commons-fileuploadartifactId>
    4. <version>1.3.1version>
    5. dependency>

    2. 在SpringMVC的配置文件中添加配置

    必须通过文件解析器的解析才能将通过表单上传的文件转换为MultipartFile对象

    1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">bean>

    3. 控制器方法

    在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常。

    关于File.separator

    比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写:
    File file1 = new File ("C:\tmp\test.txt");
    在Linux下则是这样的:
    File file2 = new File ("/tmp/test.txt");

    如果要考虑跨平台,则最好是这么写:
    File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");

    File类有几个类似separator的静态字段,都是与系统相关的,在编程时应尽量使用。

    重名问题(UUID)
    先通过 substring来截取后缀名

    再将uuid与后缀名结合

    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. }

  • 相关阅读:
    Leetcode 1431. Kids With the Greatest Number of Candies
    【Python_Process_Thread】Processing_Threading
    蓝桥杯每日一题2023.10.3
    【JS】浅谈浅拷贝与深拷贝
    计算机网络 ——TCP/IP 基础
    format前端转义
    树链剖分练习
    Social Justice Awards秋季赛学霸怎么理解?
    桥接模式:解耦抽象与实现,实现灵活多变的扩展结构
    mysql锁
  • 原文地址:https://blog.csdn.net/qq_41950447/article/details/127435073