【问题标题】:how to download file from a file server in spring boot如何在spring boot中从文件服务器下载文件
【发布时间】:2022-10-14 17:25:51
【问题描述】:

我使用 multipart 成功上传了一个文件并将实体类 ID 附加到它。发送一个 get 请求会返回一个空值。

这是我的帖子端点:

@PostMapping("/{id}/upload_multiple")
public ResponseEntity<ResponseMessage> createDocument(@PathVariable Long id,
        @RequestParam("applicationLetter") MultipartFile appLetter,
        @RequestParam("certificateOfInc") MultipartFile cInc, @RequestParam("paymentReceipt") MultipartFile payment,
        @RequestParam("taxClearance") MultipartFile tax, @RequestParam("staffsResume") MultipartFile staffs,
        @RequestParam("letterOfCredibility") MultipartFile credibility,
        @RequestParam("workCertificate") MultipartFile workCert,
        @RequestParam("consentAffidavit") MultipartFile affidavit,
        @RequestParam("collaborationCert") MultipartFile colabo, @RequestParam("directorsId") MultipartFile idcard,
        @RequestParam("membership") MultipartFile member) throws IOException {

    documentService.create(id, appLetter, cInc, payment, tax, staffs, credibility, workCert, affidavit, colabo,
            idcard, member);
    String message = "Upload successful";

    return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
}

上传的文件保存在另一个文件夹 10001 中,这是文档实体的 ID。我现在的挑战是从 10001 文件夹中获取这些文件。

这是我尝试过的,但为所有文档返回空值:

@GetMapping( "/files/{filename:.+}/{id}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
    Resource file = documentService.load(filename);
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
            .body(file);
}

我的服务等级:

private final Path root = Paths.get("documents");

 @Override
  public Resource load(String filename) {
    try {
      Path file = root.resolve(filename);
      Resource resource = new UrlResource(file.toUri());

      if (resource.exists() || resource.isReadable()) {
        return resource;
      } else {
        throw new RuntimeException("Could not read the file!");
      }
    } catch (MalformedURLException e) {
      throw new RuntimeException("Error: " + e.getMessage());
    }
  }

【问题讨论】:

  • 您是否要返回10001 下的所有文件?还是只有1个文件?

标签: java spring spring-boot


【解决方案1】:

参考这个例子:

  @GetMapping("/files")
  public ResponseEntity<List<ResponseFile>> getListFiles() {
    List<ResponseFile> files = storageService.getAllFiles().map(dbFile -> {
      String fileDownloadUri = ServletUriComponentsBuilder
          .fromCurrentContextPath()
          .path("/files/")
          .path(dbFile.getId())
          .toUriString();

      return new ResponseFile(
          dbFile.getName(),
          fileDownloadUri,
          dbFile.getType(),
          dbFile.getData().length);
    }).collect(Collectors.toList());

    return ResponseEntity.status(HttpStatus.OK).body(files);
  }

  @GetMapping("/files/{id}")
  public ResponseEntity<byte[]> getFile(@PathVariable String id) {
    FileDB fileDB = storageService.getFile(id);

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="" + fileDB.getName() + """)
        .body(fileDB.getData());
  }

【讨论】:

    【解决方案2】:

    试试这个方法来加载资源。看看它是否有效

    资源文件 = fileStorageService.loadFileAsResource(fileName);

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 2016-06-11
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多