I am trying to to upload above 1 GB file, I am using Spring Boot.
I've tried with below code, but I am getting as Out of Memory error.
public void uploadFile(MultipartFile file) throws IOException {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
String uploadFile= restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(new FileSystemResource(convert(file)), headers), String.class).getBody();
} catch (Exception e) {
throw new RuntimeException("Exception Occured", e);
}
}
private static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
The Main problem I am facing is, I am unable to convert MultipartFile to java.io.File.
I've even tried replacing FileSystemResource
with ByteArrayResource
, but still getting OOM error.
I've even tried using below code too:
private static File convert(MultipartFile file) throws IOException {
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);
}
But I am getting below exception for above snippet:
org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to org.springframework.web.multipart.MultipartFile
Could anyone please tell me on how to convert MultipartFile to java.io.File?
And also is there any other approach better than
FileSystemResource
bcoz I will have to create new file in server everytime before uploading. If file is more than 1GB, another 1 GB new file has to be created on server side, and has to manually delete that file again, which I personally didn't like this approach.