Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download File with Micronaut

My Client should receive a File from the Controller. The problem is that the Client is only receiving a string. How can I get the returned stream from the Controller?

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:

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

public String getBackup(String dataBaseName) {
    return client.toBlocking().retrieve(HttpRequest.GET("/backup/" + dataBaseName));
}
like image 802
davebo92123 Avatar asked Jun 19 '20 09:06

davebo92123


1 Answers

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...
}
like image 107
cgrim Avatar answered Nov 18 '22 21:11

cgrim