Sending files from Micronaut applications
Tags: java, micronaut
Published: 2024-03-24 16:52:34

## Intro
In this time, I will try sending files to my Micronaut application.

* [[Micronaut] Receiving multipart/form-data](https://dev.to/masanori_msl/micronaut-receiving-multipartform-data-50ni)

## multipart/form-data
#### FileController.java
```java
...
    @Get("/send")
    public String sendSample() {
        File file1 = new File("C:\\Files\\sample1.xlsx");
        File file2 = new File("C:\\Files\\sample2.xlsx");
        MultipartBody requestBody = MultipartBody.builder()
                .addPart("file1", file1.getName(), MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE, file1)
                .addPart("file2", file2.getName(), MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE, file2).build();
        HttpRequest<?> req = HttpRequest.POST("http://localhost:8086/files/sample",
                requestBody).contentType(MediaType.MULTIPART_FORM_DATA);
        return Mono.from(httpClient.retrieve(req)).block();
    }
...
```

## application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
To send specific type files like spreadsheets(xlsx), I get a byte array from the file and set as the request body data.

#### FileController.java
```java
...
    @Get("/compute")
    public Mono<ComputeResult> compute() {
        File file = new File("C:\\Files\\sample1.xlsx");
        byte[] fileData = Files.readAllBytes(file.toPath());
        HttpRequest<?> req = HttpRequest.POST("http://localhost:8086/compute",
                fileData)
                .contentType(MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE);
        return Mono.from(httpClient.retrieve(req)).map(result -> {
            // Converting the JSON value into a class what is named ComputeResult.
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.readValue(result, ComputeResult.class);
            } catch (JsonProcessingException e) {
                return null;
            }
        });
```

## text/json
#### ComputingStatusRequest.java
```java
package jp.masanori.dto;

import io.micronaut.serde.annotation.Serdeable;

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

@Serdeable
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class ComputingStatusRequest {
    public String RequestID;    
}
```
#### FileController.java
```java
...
    @Get("/status")
    public Mono<ComputeResult> getStatus() {
        ComputingStatusRequest requestId = new ComputingStatusRequest();
        requestId.RequestID = startResult.getRequestId();
        ObjectMapper mapper = new ObjectMapper();
        HttpRequest<?> req = HttpRequest.POST("http://localhost:8086/status", 
            mapper.writeValueAsString(requestId))
            .contentType(MediaType.TEXT_JSON_TYPE);
        return Mono.from(httpClient.retrieve(req)).map(result -> {
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.readValue(result, ComputeResult.class);
            } catch (JsonProcessingException e) {
                return null;
            }
        });
    }
...
```

* [Micronaut HTTP Client](https://guides.micronaut.io/latest/micronaut-http-client-gradle-java.html)
* [【WebAPI】multipart/form-dataでファイルをアップロードする 【Java】 - 株式会社シベスピ - 従業員ブログ](https://chivsp.hatenablog.com/entry/2022/10/03/090000)