Home > Back-end >  Consume Json with excel file in spring boot rest api
Consume Json with excel file in spring boot rest api

Time:07-21

Is it possible with spring boot and for example apache poi to get POST request json format with excel file inside? for example :

POST api/testrequest/ 
Content-Type: application/json  //(maybe another type?)
{
    "searchKey": "test1",
    "searchValue": file.excel
}

And fetch it to Object?

Now I did something like this :

Controller method :

@PostMapping(
      value = "excelentity",
      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
  public String getExcelAndParseItToEntity(@RequestBody ExcelTemplate file) {
    String fileName = file.getFile().getOriginalFilename();
    log.info(fileName);
    
    return "test case";
  }

And Java Object :

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ExcelTemplate {
    private MultipartFile file;
    private String name;
}

But it doesn't work

CodePudding user response:

You can't include it directly but you can encode it as string.

The client sending that json request to your spring boot application can encode the file to base64 and include the resulting string in the json as text.

Something like that:

byte[] fileContent = readExcelFile(file); // Use InputStreams to read all bytes of the excel

String encodedFile = Base64.getEncoder().encodeToString(fileContent);

doRequest(encodedFile); // Do request, set 'encodedFile' as value of 'searchValue' in json

Your json would then look something like that:

{
    "searchKey": "test1",
    "searchValue": "SGVsbG8gU3RhY2tPdmVyZmxvdyE=..."
}

In your spring boot application simply decode it to bytes again and save it as file or use it directly with a ByteArrayInputStream.

var searchValue = getFromJson(json); // get the value from your json / dto

byte[] decodedBytes = Base64.getDecoder().decode(searchValue);

// Save to a file then use it
saveToFile(decodedBytes); 
// Or
// Use it directly as InputStream without saving it to file
var inputStream = new ByteArrayInputStream(decodedBytes); 

See this baeldung tutorial for more information on how to use Base64: https://www.baeldung.com/java-base64-encode-and-decode
And this one for the ByteArrayInputStream: https://www.baeldung.com/convert-byte-array-to-input-stream

  • Related