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

McLovin picture McLovin · Jun 17, 2016 · Viewed 18.1k times · Source

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

Bernhard picture Bernhard · Jul 5, 2016

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