使用 Spring 5 下载 PDF 文件时出错

Tar*_*nyk 1 java spring reactive-programming project-reactor

我尝试使用 Spring 5 下载 PDF 文件。以下是我的代码:

@RequestMapping(path = "/pdf", method = { RequestMethod.POST }, produces = MediaType.APPLICATION_PDF_VALUE)
public Mono<ResponseEntity<Resource>> getPDF(ServerHttpRequest httpRequest) 
{
    File file = new File(filepath);
    ResponseEntity<Resource> resource = getResource(file);
    return Mono.justOrEmpty(resource);
}

public ResponseEntity<Resource> getResource(File file) {
   final InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
   HttpHeaders headers = new HttpHeaders();
   headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName());
   headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
   headers.add("Pragma", "no-cache");
   headers.add("Expires", "0");
   return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_PDF).contentLength(file.length()).body(new InputStreamResource(inputStream));
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下异常:

java.lang.NoSuchMethodError: reactor.core.publisher.Flux.doOnDiscard(Ljava/lang/Class;Ljava/util/function/Consumer;)Lreactor/core/publisher/Flux;

在 org.springframework.core.io.buffer.DataBufferUtils.readByteChannel(DataBufferUtils.java:105) 在 org.springframework.core.io.buffer.DataBufferUtils.read(DataBufferUtils.java:202) 在 org.springframework.core.io .buffer.DataBufferUtils.read(DataBufferUtils.java:170) at org.springframework.core.codec.ResourceEncoder.encode(ResourceEncoder.java:76) at org.springframework.core.codec.ResourceEncoder.encode(ResourceEncoder.java:40) ) 在

...

Kar*_*cki 5

您的依赖项有错误。您使用的是不兼容版本的 Spring Framework 和 Project Reactor:

java.lang.NoSuchMethodError: reactor.core.publisher.Flux.doOnDiscard(Ljava/lang/Class;Ljava/util/function/Consumer;)Lreactor/core/publisher/Flux;

更正您的项目设置,您可以使用Spring Initializer查看正确设置的样子。