美文网首页
SpringBoot 使用问题

SpringBoot 使用问题

作者: 寒沁 | 来源:发表于2024-05-13 18:45 被阅读0次

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

    1. 下载本地资源文件,本地可以下载,jar包下载不了,如何解决?原因是什么?
    • 问题描述
      controller下载项目相对路径文件,用 ResourceUtils.getURL("classpath:").getPath() + "static/" + fileName; 获取资源,本地启动能获取,jar包形式启动获取不到,
    • 修复方案
      改成 “ this.getClass().getClassLoader().getResourceAsStream("static/" + fileName) ” 方式可以
      具体下载代码
       # 修改前
      @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)));
      }
    
    • 原因分析

    相关文章

      网友评论

          本文标题:SpringBoot 使用问题

          本文链接:https://www.haomeiwen.com/subject/jdipfjtx.html