Will Spring hold contents in memory or stores in the disk?
Asked Answered
D

4

14

When a file say 100 MB size is uploaded from browser will Spring hold whole data in memory or stores in the disk temporarily. After going through Spring doc I know how to set a temp dir but I want to know what will happen if I don't mention that.

Am having following declaration :

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

Bean :

public class FileHolder {

    private MultipartFile file;

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    public MultipartFile getFile() {
        return file;
    }
}

Will the "file" object in the above bean hold that 100 MB data ?

Davidson answered 23/12, 2009 at 12:50 Comment(0)
A
16

A bit more digging in the javadoc shows that the default maximum in-memory size is 10240 bytes. From that I'd assume that any upload less than 10kB is held in memory, anything larger will be stored on disk. If you don't specify the disk location, it'll likely use a default (I'd guess it'll use the system default tmp directory).

Aun answered 23/12, 2009 at 12:56 Comment(1)
According to this answer, the default location is System.getProperty("java.io.tmpdir").Necroscopy
C
5

In spring boot, spring.servlet.multipart.file-size-threshold specifies the size threshold after which files will be written to disk.

The default value of the property is zero. It means by default, it stores all files in a temporary location (can be configured via spring.servlet.multipart.location).

Link: spring boot properties

Be aware of some bugs on the implementations here: https://github.com/spring-projects/spring-boot/issues/9073

Cepheus answered 24/12, 2018 at 13:39 Comment(0)
O
2

If you don't set the temp directory CommonsMultipartResolver will save temporary files to the servlet container's temporary directory.

The "file" object in your example doesn't hold the data it similar to a java.io.File reference. You need to get the data with file.getBytes().

Ogre answered 23/12, 2009 at 16:29 Comment(0)
D
2

Yes, but if it's stored on disk it will be deleted after the request has been processed. You can set the threshold for when it will be stored on disk:

In your multipartresolver bean definition, e.g.:

<property name="maxUploadSize" value="1000000" /> 
<property name="maxInMemorySize" value="1000" /> 

If it's held in memory, you could store it in the session and process it in the next request, for instance, such as if you're waiting for a user confirmation.

Dejesus answered 23/12, 2009 at 16:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.