Spring - How to stream large multipart file uploads to database without storing on local file system [duplicate]

ghz 1years ago ⋅ 640 views

Question

This question already has answers here :

[SpringBoot: Large Streaming File Upload Using Apache Commons FileUpload](/questions/32782026/springboot-large-streaming-file-upload-using- apache-commons-fileupload) (5 answers)

Closed 2 years ago.

Spring boot's default MultiPartResolver interface handles the uploading of multipart files by storing them on the local file system. Before the controller method is entered, the entire multipart file must finish uploading to the server.

We are storing all of our uploaded files directly to a database and our servers have a very small disk quota, so if a large file is uploaded, we are seeing an IOExeption - Disk quota exceeded.

Is there a way to get the stream directly from the client's incoming request before Spring's MultiPartResolver stores the file on the local filesystem so the we can stream directly to our db?


Answer

You could use apache directly, as described here https://commons.apache.org/proper/commons-fileupload/streaming.html.

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request) throws IOException, FileUploadException {

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();
                //...
            }
        }
    }
}

Make sure to disable springs multipart resolving mechanism.

application.yml:

spring:
   http:
      multipart:
         enabled: false