Issue
My SpringBoot API receives multipart file. Then using RestTemplate I am sending same to different API. It works fine!!!
Problem here is its storing multipart file on server harddisk. My API should just act as an intermediate service between frontend and another API endpoint.
I do not want to store received file locally One thing I can do is delete after uploaded to different API.
Is there any better way we do same thing i.e. without storing on server or automatic delete from server.
My code is as below Controller
@PostMapping(value = "/uploadFile", consumes = { "multipart/form-data" })
public SomePojoObject uploadFile(@RequestParam("file") MultipartFile mFile,
@RequestParam("metaData") String metaData) {
return service.uploadFile(mFile, metaData);
}
And Service code is as below
private SomePojoObject uploadFile(MultipartFile mFile, String metaData) {
File file = convertFile(mFile);
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("FILE", new FileSystemResource(file));
map.add("metaData", metaData);
// Some more logic of resttemplate to upload document to server
}
public File convertFile(MultipartFile mFile) {
File file = new File(mFile.getOriginalFilename());
try {
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(mFile.getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printstackTrace();
}
return file;
}
Solution
Finally found a rather very simple way to achieve above.
There is no need to convert it to file.!!!!
private SomePojoObject uploadFile(MultipartFile mFile, String metaData) {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("FILE", mFile.getResource());
map.add("metaData", metaData);
// Some more logic of resttemplate to upload document to server
}
Answered By - Aniket
Answer Checked By - Senaida (JavaFixing Volunteer)