Reputation: 991
I have the following code which I use for posting a file to a service and it works fine. The only problem I have, is that I have to write a temporary file to get a FileSystemResource for posting the object with the restTemplate
Is there anyway I can adapt the following code so that I dont have to write a temporary file?
public String postNewIcon2(Integer fileId, MultipartFile multiPartfile) {
LOG.info("Entered postNewIcon");
Map<String, Object> params = getParamsWithAppKey();
params.put("fileId", fileId);
String result = null;
File tempFile = null;
try {
String originalFileNameAndExtension = multiPartfile.getOriginalFilename();
String tempFileName = "c:\\temp\\image";
String tempFileExtensionPlusDot = ".png";
tempFile = File.createTempFile(tempFileName, tempFileExtensionPlusDot);
multiPartfile.transferTo(tempFile);
FileSystemResource fileSystemResource = new FileSystemResource(tempFile);
// URL Parameters
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", fileSystemResource);
// Post
result = restTemplate.postForObject(getFullURLAppKey(URL_POST_NEW_ICON), parts, String.class, params);
} catch (RestClientException restClientException) {
System.out.println(restClientException);
} catch (IOException ioException) {
System.out.println(ioException);
} finally {
if (tempFile != null) {
boolean deleteTempFileResult = tempFile.delete();
LOG.info("deleteTempFileResult: {}", deleteTempFileResult);
}
}
return result;
}
Thank you
Upvotes: 4
Views: 9251
Reputation: 84
MultipartFile needs to have some temp location. Please try this code, to get physical file:
private File getTempFile(MultipartFile attachment){
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) attachment;
DiskFileItem diskFileItem = (DiskFileItem) commonsMultipartFile.getFileItem();
return diskFileItem.getStoreLocation();
}
Upvotes: 1
Reputation: 991
Answer with help with Kresimir Nesek and this link Sending Multipart File as POST parameters with RestTemplate requests
The following code did the trick - no need for a temporary file now
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
final String filename="somefile.txt";
map.add("name", filename);
map.add("filename", filename);
ByteArrayResource contentsAsResource = new ByteArrayResource(content.getBytes("UTF-8")){
@Override
public String getFilename(){
return filename;
}
};
map.add("file", contentsAsResource);
String result = restTemplate.postForObject(urlForFacade, map, String.class);
Upvotes: 11