Download File with Micronaut

davebo92123

My Client should receive a File from the Controller. I don´t know how the Client should be implemented. This is my Controller:

@Get("/{databaseName}")
MutableHttpResponse < Object > createDatabaseBackup(String databaseName) {
    InputStream inputStreamDatabaseBackup = backupTask.exportBackup(databaseName);
    return HttpResponse.ok(new StreamedFile(inputStreamDatabaseBackup, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}

Here is my client, the problem is that the Client is only receiving a string. How can I get now the returned stream from the Controller?

Client:

@Inject
@Client("${agent.connection-url}")
private RxHttpClient client;

public String getBackup(String dataBaseName) {
    return client.toBlocking().retrieve(HttpRequest.GET("/backup/" + dataBaseName));
}
cgrim

You have to define that you need response as a byte[] array:

public byte[] getBackup(String databaseName) {
    return client.toBlocking().retrieve(HttpRequest.GET("/backup/" + databaseName), byte[].class);
}

Then you can convert byte array into any stream you want.

Or you can use the reactive way:

public Single<byte[]> getBackup(String databaseName) {
    return client.retrieve(HttpRequest.GET("/backup/" + databaseName), byte[].class)
        .collect(ByteArrayOutputStream::new, ByteArrayOutputStream::writeBytes)
        .map(ByteArrayOutputStream::toByteArray);
}

Or you can define declarative client:

@Client("${agent.connection-url}")
public interface SomeControllerClient {

    @Get(value = "/{databaseName}", processes = MediaType.APPLICATION_OCTET_STREAM)
    Flowable<byte[]> getBackup(String databaseName);

}

And then use it where you need:

@Inject
SomeControllerClient client;

public void someMethod() {
    client.getBackup("some-database")
        .collect(ByteArrayOutputStream::new, ByteArrayOutputStream::writeBytes)
        .map(ByteArrayOutputStream::toByteArray)
        .otherStreamProcessing...
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事