If you're using Spring you can use the getSize() method.

Here is the definition.

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html

And here some examples

http://www.mkyong.com/spring-mvc/spring-mvc-file-upload-example/

The last modified date value is part of the filesystem (Operating System), so you can not transfer this metadata with the file.

If you send the value in other field, this is not safe because any user could send whatever value they want. Another thing to notice is that the last modified date depends on the operatingsystem date. Ss if the user change its computer date the date that you recieve it's not real.

Answer from reos on Stack Overflow
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Discussions

rest - How to determine the file size for multi-part POST request Java? - Stack Overflow
The only best guess is to read the Content-Length which may not even always be present and even then it's the size of the whole multipart data, usually encoded in base-64. If your client-side uploads the file using Javascript, you could get the file size there and append it to the ... More on stackoverflow.com
🌐 stackoverflow.com
September 4, 2018
Get correct file size from Spring MultipartFile - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
java - Read current max multipartfile size - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
http headers - How to get the real file size of a file in a multipart/form-data request - Stack Overflow
As the title says, I need to get the real filesize of a file posted as a multipart/form-data request. I'm based in the JSF world but I think the problem is technology-agnostic (only depends on HTT... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › web › multipart › MultipartFile.html
MultipartFile (Spring Framework 7.0.8 API)
Return the original filename in the client's filesystem. ... Return a Resource representation of this MultipartFile. ... Return the size of the file in bytes.
🌐
Baeldung
baeldung.com › home › java › java io › file size in java
File Size in Java | Baeldung
November 29, 2023 - The above code first checks if the file exists and if it does, it calculates and prints its size in bytes, kilobytes, megabytes, and gigabytes. In this tutorial, we illustrated examples of using Java and Apache Commons IO to calculate the size of a file in the file system.
🌐
Stack Overflow
stackoverflow.com › questions › 65291218 › read-current-max-multipartfile-size
java - Read current max multipartfile size - Stack Overflow
@Autowired Environment env; .... System.out.println(env.getProperty("spring.servlet.multipart.max-file-size")); System.out.println(env.getProperty("servlet.multipart.max-file-size")); System.out.println(env.getProperty("multipart.max-file-size")); ...
Find elsewhere
🌐
Spring
docs.spring.io › spring-framework › docs › 5.0.0.M4_to_5.0.0.M5 › Spring Framework 5.0.0.M4 › org › springframework › web › multipart › MultipartFile.html
MultipartFile
Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content. ... Return the size of the file in bytes.
🌐
GitConnected
levelup.gitconnected.com › how-to-handle-file-uploads-in-java-spring-boot-5fb1eb81ada0
How to Handle File Uploads in Java Spring Boot | by Kunal Nalawade | Level Up Coding
January 9, 2023 - This prevents a malicious user from uploading an unnecessarily large file. Use the MultipartFile object’s getSize() method to get the size of a file in bytes.
Top answer
1 of 1
3

Here's what you need to do:

  1. Use custom annotation validation for all your input with different sizes.
  2. Set a default maximum size that Spring Boot can accept in your application.properties

To achieve step 1, lets say you have an Entity: Post

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.*;

@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String image;

    @Transient
    private MultipartFile imageContent;

    // Getters and setters, constructors, etc.
}

With an interface, PostImageSize

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = ImageSizeValidation.class)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface PostImageSize {

    String message() default "Invalid image size";

    long maxSize() default 5 * 1024 * 1024; // Default size is 5MB

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

and the class ImageSizeValidation mentioned in PostImageSize interface

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.web.multipart.MultipartFile;

public class ImageSizeValidation implements 
ConstraintValidator<PostImageSize, MultipartFile> {

    private long maxSize;

    @Override
    public void initialize(PostImageSize constraintAnnotation) {
        this.maxSize = constraintAnnotation.maxSize();
    }

    @Override
    public boolean isValid(MultipartFile multipartFile, 
    ConstraintValidatorContext cxt) {
        return multipartFile == null || multipartFile.getSize() <= 
        maxSize;
    }
}

Once you have set this up, using the annotation @PostImageSize in your entity will enable custom validation.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String image;

    @PostImageSize(message = "This image must not be more than 5MB")
    private MultipartFile imageContent;

    // Getters and setters, constructors, etc.
}

After this, you can customize the size according to the annotations you have and include in your entity which will enable it.

// Customizing to 1MB
@PostImageSize(message = "This image must not be more than 1MB", maxSize = 1024 * 1024)
private MultipartFile imageContent;

For step 2 in your application.properties

# Multipart settings
spring.servlet.multipart.max-file-size=256MB
spring.servlet.multipart.max-request-size=256MB
spring.servlet.multipart.enabled=true

Goodluck !!!

🌐
Medium
gainjavaknowledge.medium.com › spring-boot-file-upload-example-e5c516e681a9
Spring Boot file upload example. In this article, You’ll learn how to… | by Gain Java Knowledge | Medium
November 17, 2020 - #Multipart Properties # Enable multipart uploads spring.servlet.multipart.enabled=true # Threshold after which files are written to disk. spring.servlet.multipart.file-size-threshold=2KB # Max file size. spring.servlet.multipart.max-file-size=2MB # Max Request Size spring.servlet.multipart.max-request-size=2MB · ## File Storage Properties # All files uploaded through the REST API will be stored in this… ... The Java programming language is one of the most popular languages today.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-get-file-size
Java get file size | DigitalOcean
August 3, 2022 - If you are already using Apache Commons IO in your project, then you can use FileUtils sizeOf method to get file size in java.
🌐
YouTube
youtube.com › kb tutorials
MultipartFile Basics In SpringBoot | Get Uploaded FIle Info using MultipartFile in spring boot - YouTube
In this video we will learn basics about multipartfile in springboot.Like uploaded file name,fileType,isFile open,isReadable,file length and file data as byt...
Published   April 22, 2023
Views   13K
🌐
Spring
docs.spring.io › spring-framework › docs › 3.0.6.RELEASE_to_3.1.0.BUILD-SNAPSHOT › 3.1.0.BUILD-SNAPSHOT › org › springframework › web › multipart › MultipartFile.html
org.springframework.web.multipart Interface MultipartFile
Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content. ... Return the size of the file in bytes.
🌐
JAXB
javaee.github.io › tutorial › servlets011.html
Uploading Files with Java Servlet Technology
Servlets that are annotated with @MultipartConfig can retrieve the Part components of a given multipart/form-data request by calling the request.getPart(String name) or request.getParts() method. The @MultipartConfig annotation supports the following optional attributes. location: An absolute path to a directory on the file system. The location attribute does not support a path relative to the application context. This location is used to store files temporarily while the parts are processed or when the size of the file exceeds the specified fileSizeThreshold setting.
🌐
Reddit
reddit.com › r/askprogramming › java: help with large spring multipart file upload
r/AskProgramming on Reddit: Java: Help with large spring multipart file upload
October 4, 2019 -

Hey Reddit!

So i've set up a spring boot endpoint that looks like this:

@PutMapping(value = "/user/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public  ResponseEntity handleUserFileUpload(@RequestHeader("Authorization")  String token, @RequestParam("file") MultipartFile file,RedirectAttributes redirectAttributes) {

and i can upload files file when they are under 35MB roughly. When i start to upload larger files i get a heap space issue and the upload fails :/

Is there a way i can get past this? Like a setting to set max heap size?

Thanks in advance :D