I need to upload two kinds of files for one the maximum file size is 10MB and for another file size is 50KB. so I created an environment variable in the application.properties file there I gave the value as 1KB. now my question is how to change the file size 1KB to 50KB and 10MB at runtime. I tried to do it in many ways but it's now working for me. Environment variable screenshot
applicationl.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/import_csv_mysql
spring.datasource.username=root
spring.datasource.password=Manoj2@@@
spring.datasource.platform=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#fileSize=2KB
#spring.servlet.multipart.max-file-size=${fileSize}
#spring.servlet.multipart.max-request-size=${fileSize}
In this FileSizeConfiguration class I'm getting environment variable value and store in the "size" and created a setter.
@Configuration
public class FileSizeConfiguration {
@Value("${fileSize}")
private String size;
public void setSize(String size) {
this.size = size;
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.parse(size));
factory.setMaxRequestSize(DataSize.parse(size));
System.out.println(size);
return factory.createMultipartConfig();
}
}
controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private FileSizeConfiguration fileSizeConfiguration;
@GetMapping("users/add")
private void addUsers(@RequestParam("File")MultipartFile file) throws Exception{
//....
}
@GetMapping("file/add")
private void addFile(@RequestParam("File")MultipartFile file) throws Exception{
//....
}
//using this method changing the file size
@PostMapping("filesize/change")
private void changeSize(@RequestParam String size){
fileSizeConfiguration.setSize(size);
}
}
here before calling the users/add i will set the file size to 50KB using the changefilesize/change, and for file/add i will change the file size to 10MB. but it's not working as i thought. always it giving the error " exceeds the configured maximum (1024) 1KB".
postman screenshot for adding file
postman screenshot for changing file size
I will always change the filesize and will import the file, even though I getting the same error, I don't know why the maximum file size is not changing. but while printing the size value I'm getting the new value what i changed.