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

时间:2019-03-06 09:48:35

标签: 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));
}

但是我遇到了以下异常:

  

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)     在   org.springframework.core.codec.ResourceEncoder.encode(ResourceEncoder.java:76)     在   org.springframework.core.codec.ResourceEncoder.encode(ResourceEncoder.java:40)     在

     

...

2 个答案:

答案 0 :(得分:4)

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

  

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

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

答案 1 :(得分:1)

我已经通过解决依赖冲突解决了该问题。我有两个reactor-core库的不同版本。我已经删除了它们,并下载了最新的version