SpringBoot 使用问题

2024-05-13  本文已影响0人  寒沁

项目会碰到很多问题,记录一下

  1. 下载本地资源文件,本地可以下载,jar包下载不了,如何解决?原因是什么?
   # 修改前
  @PostMapping("/download")
  public ResponseEntity<InputStreamResource> donwload(HttpServletResponse response, String fileName) {
      try {
          String courseFile = ResourceUtils.getURL("classpath:").getPath() + "static/" + fileName;
          # jar包打印出来的路径为 : file:/xxx.jar!/BOOT-INF/classes!/static/文件名xlsx
          logger.info("common download tmp courseFile={}", courseFile);
          FileSystemResource file = new FileSystemResource(courseFile);
          HttpHeaders headers = new HttpHeaders();
          headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
          headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
          headers.add("Pragma", "no-cache");
          headers.add("Expires", "0");

          return ResponseEntity
                  .ok()
                  .headers(headers)
                  .contentLength(file.contentLength())
                  .contentType(MediaType.parseMediaType("application/octet-stream"))
                  .body(new InputStreamResource(file.getInputStream()));
      } catch (IOException e) {
          e.printStackTrace();
      }
      return null;
  }

  # 修改后
  @PostMapping("/download")
  public ResponseEntity<InputStreamResource> donwload(HttpServletResponse response, String fileName) {
      HttpHeaders headers = new HttpHeaders();
      headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
      headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
      headers.add("Pragma", "no-cache");
      headers.add("Expires", "0");

      return ResponseEntity
              .ok()
              .headers(headers)
              .contentType(MediaType.parseMediaType("application/octet-stream"))
              .body(new InputStreamResource(this.getClass().getClassLoader().getResourceAsStream("static/" + fileName)));
  }
上一篇 下一篇

猜你喜欢

热点阅读