Spring Boot MultipartFile 资源[文件]无法解析为绝对文件路径

问题描述 投票:0回答:1

这可能是因为什么? 该目录位于 /opt/docs 中,该文件存在。文件已上传,但无法下载回来

也许我错过了一些东西,我认为问题是convertFileFromPath,帮我弄清楚






@PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE})
public AttachmentResponseDto uploadFile(@RequestPart AttachmentRequestDto dto, @RequestPart MultipartFile file) throws IOException {
    return service.saveAttachment(file, dto.getType());
}

@GetMapping(value = "/download/{id}")
public AttachmentResponseDto downloadById(@PathVariable Long id) throws IOException {
    return service.getFileById(id);
}

@Value("${file.storage.docs}")
private String docDirectory;

@Override
public AttachmentResponseDto saveAttachment(MultipartFile file, String type) throws IOException {
    AttachmentResponseDto responseDto = new AttachmentResponseDto();
    String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
    String fileName = Objects.requireNonNull(type).concat("№" + UUID.randomUUID().toString()).concat("." + extension);
    Path root = Paths.get(docDirectory);
    Files.copy(file.getInputStream(), root.resolve(fileName));
    responseDto.setFilePath(root.toString().concat("/").concat(fileName));
    responseDto.setType(type);
    responseDto.setExtension(extension);
    responseDto.setName(fileName);
    Attachments attachments = convertDtoToEntity(responseDto);
    Attachments saved = repository.save(attachments);
    responseDto.setAttachmentId(saved.getId());
    return responseDto;
}

@Override
public AttachmentResponseDto getFileById(Long id) throws IOException {
    Attachments getById = repository.findById(id).get();
    AttachmentResponseDto responseDto = convertDtoToEntity(getById);
    responseDto.setFile(convertFileFromPath(getById));
    return responseDto;
}

@Override
public MultipartFile convertFileFromPath(Attachments attachments) throws IOException {
    return new MockMultipartFile(attachments.getName(), new FileInputStream(attachments.getPath()));
}






java spring-boot attachment multipartfile
1个回答
0
投票

MockMultipartFile 是一个测试依赖项,切勿在非测试代码中使用。此外,MultipartFile 仅用于上传到您的 API,而不用于下载文件。下载时,只需返回资源即可。

这个应该更符合你的需要。

@GetMapping(value = "/download/{id}")
public Resource downloadById(@PathVariable Long id) throws IOException {
    // ...
   Resource resource = new InputStreamResource(new FileInputStream(file));
  return resource;
}
© www.soinside.com 2019 - 2024. All rights reserved.