Access File in multipart/form-data in a stream like fashion in Spring Boot rest controller

Viewed 666

following scenario: Service A receives a multipart/form-data request and needs to forward it to Service B. Because the file in the request can be of arbitrary size, Service A needs to stream the file to Service B as soon as possible. At the moment Service A can receive the requests but Spring Boot will load the whole request/file into memory resulting in a really high memory footprint. I also tried the often suggested apache commons-fileupload package but without the expected result.

This leads me to the following question:

Is it even possible in spring boot to access the incomming http request in a stream like manner without loading the whole thing into the memory or a file ?

Thank you!

1 Answers

Unfortunately, I don't think it's possible to receive a value without loading it into either memory or onto a temporary location on the disk.

If you look at the configuration, the value spring.servlet.multipart.file-size-threshold=2KB defines at what point Spring should stop loading objects into memory, and instead start writing them to the disk.

If you still want to use a stream, it's easily done by accepting a MultipartFile and calling "getInputStream()"

@PostMapping
public void yourRequest(@RequestParam("file") MultipartFile file) {
    InputStream inputStream = file.getInputStream();

    // your code
    ...
}
Related