无法创建生成的 HTTP 客户端所需的 return 类型,因为没有从 ByteBuffer 到 class java.io.File 的类型转换器:Micronaut

Cannot create the generated HTTP client's required return type, since no TypeConverter from ByteBuffer to class java.io.File : Micronaut

下面是使用 micronaut 将文件作为 rest 响应发送到客户端的服务器端代码。

@Get(value = "/downloadFile", produces = MediaType.APPLICATION_OCTET_STREAM )
public HttpResponse<File> downloadDocument() throws IOException {

    File sampleDocumentFile = new File(getClass().getClassLoader().getResource("SampleDocument.pdf").getFile());

    return HttpResponse.ok(sampleDocumentFile).header("Content-Disposition", "attachment; filename=\"" + sampleDocumentFile.getName() + "\"" );
}

下面是调用上述端点的客户端。

@Client(value = "/client")
public interface DownloadDocumentClient {

@Get(value = "/downloadDocument", processes = MediaType.APPLICATION_OCTET_STREAM)
public Flowable<File> downloadDocument();

}

尝试如下检索文件:-

Flowable<File> fileFlowable = downloadDocumentClient.downloadDocument();
    Maybe<File> fileMaybe = fileFlowable.firstElement();
    return fileMaybe.blockingGet();

获取异常

io.micronaut.context.exceptions.ConfigurationException: Cannot create the generated HTTP client's required return type, since no TypeConverter from ByteBuffer to class java.io.File is registered

您不能使用 File 实例发送文件数据,因为它只包含路径而不包含文件内容。您可以使用字节数组发送文件内容。

以这种方式更新控制器:

@Get(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM)
public HttpResponse<byte[]> downloadDocument() throws IOException, URISyntaxException {
    String documentName = "SampleDocument.pdf";
    byte[] content = Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(documentName).toURI()));
    return HttpResponse.ok(content).header("Content-Disposition", "attachment; filename=\"" + documentName + "\"");
}

客户端会变成这样:

@Get(value = "/download", processes = MediaType.APPLICATION_OCTET_STREAM)
Flowable<byte[]> downloadDocument();

最后客户电话:

Flowable<byte[]> fileFlowable = downloadDocumentClient.downloadDocument();
Maybe<byte[]> fileMaybe = fileFlowable.firstElement();
byte[] content = fileMaybe.blockingGet();

更新: 如果您需要将接收到的字节(文件内容)保存到客户端计算机(容器)上的文件中,那么您可以这样做,例如:

Path targetPath = Files.write(Paths.get("target.pdf"), fileMaybe.blockingGet());

如果你真的需要 File 而不是 Path 的实例来进行进一步处理,那么只需:

File file = targetPath.toFile();