Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot multipart file upload, remove the local server copy

These days I am developing a rest API which provides the functionality of uploading the images. Everything works perfectly however my backend server location gets filled up with the image copies. It looks like the spring keeps a local copy of every image it uploads. Is there any option that we can disable the saving of local copy. I did a quick look at the documentation and I could find below properties for multipart files.

# MULTIPART (MultipartProperties)
spring.servlet.multipart.enabled=true # Whether to enable support of 
multipart uploads.
spring.servlet.multipart.file-size-threshold=0 # Threshold after which files 
are written to disk. Values can use the suffixes "MB" or "KB" to indicate 
megabytes or kilobytes, respectively.
spring.servlet.multipart.location= # Intermediate location of uploaded 
files.
spring.servlet.multipart.max-file-size=1MB # Max file size. Values can use 
the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively.
spring.servlet.multipart.max-request-size=10MB # Max request size. Values 
can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, 
respectively.
spring.servlet.multipart.resolve-lazily=false # Whether to resolve the 
multipart request lazily at the time of file or parameter access.

There is a location we can tell the system to copy the local copy, but there is no option to disable it. Do you guys have any suggestion for this? Do we need to have a separate program to purge these local image copies and save the space?

Thanks, Keth

like image 545
keth Avatar asked Nov 04 '25 22:11

keth


2 Answers

I'm aware that this topic is a little old, but it's the first one that came out during my google search.

Today I face the same problem. After a little research, it turns out that Spring automatically does this cleaning. In my case, the cleaning was not done because I forgot to close the streams related to the received file.

I hope it helps.

like image 81
Léo Avatar answered Nov 07 '25 14:11

Léo


I converted the multipart to Java File object and Deleted it manually after using it

public static File convertMultiPartToFile(MultipartFile file) throws IOException {
    File convFile = new File(file.getOriginalFilename());
    FileOutputStream fos = new FileOutputStream(convFile);
    fos.write(file.getBytes());
    fos.close();
    return convFile;
  }

then called file.delete method

File tempFile = FileUtils.convertMultiPartToFile(file);
logger.info("Deleting temp file on path " + tempFile.getAbsolutePath());
boolean deleted = tempFile.delete();
like image 30
Usman Avatar answered Nov 07 '25 15:11

Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!