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
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);
                        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();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With