spring 如何在Sping Boot 中从文件服务器下载文件

uinbv5nw  于 2022-10-31  发布在  Spring
关注(0)|答案(3)|浏览(268)

我成功地使用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中,文件夹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());
    }
  }

我的实体类:

@Entity
@Getter
@Setter
public class Documents {

    @Id
    @Column(nullable = false, updatable = false)
    @SequenceGenerator(
            name = "primary_sequence",
            sequenceName = "primary_sequence",
            allocationSize = 1,
            initialValue = 10000
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "primary_sequence"
    )
    private Long id;

    @Column(nullable = false)
    private String applicationLetter;

    @Column(nullable = false)
    private String certOfIncorporation;

    @Column(nullable = false)
    private String paymentReceipt;

    @Column(nullable = false)
    private String taxClearance;

    @Column(nullable = false)
    private String staffsResume;
}
ebdffaop

ebdffaop1#

请参考以下示例:

@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());
  }
gg58donl

gg58donl2#

请尝试此方法加载资源。以查看是否有效
资源文件=文件存储服务.loadFileAsResource(文件名);

ryoqjall

ryoqjall3#

请尝试以下代码

@GetMapping( "/files/{filename:.+}/{id}")
public void getFile(@PathVariable String filename, HttpServletRequest request, final HttpServletResponse response) {
    BufferedInputStream bufferedInputStream = null;
    try {
        File file = ...;

        response.setHeader("Cache-Control", "must-revalidate");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-disposition", "attachment; ");

        bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(bufferedInputStream, response.getOutputStream());

    } catch (Exception e) {
    logger.error(e.getMesssage(), e);
    } finally {
        try {
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception ex) {
            logger.error(ex);
        }

        try {
            if (bufferedInputStream != null)
                bufferedInputStream.close();
        } catch (Exception ex) {
            logger.error(ex);
        }
    }
}

我不确定它是否适用于您的系统,但对我来说,我仍然使用这种方法来正常下载文件。

相关问题