Tag Archives: java

Upload MultipartFile using Spring RestTemplate

public boolean uploadAttachment(MultipartFile file) {
        boolean success = false;
        if (!file.isEmpty()) {
            try {
                ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
                    @Override
                    public String getFilename() {
                        return file.getOriginalFilename();
                    }
                };
                LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
                map.add("file", fileAsResource);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
                String url = "http://localhost:8084/attachments";

                ResponseEntity<String> response = restTemplate.exchange(url,
                        HttpMethod.POST,
                        entity,
                        String.class);
                if (response.getStatusCode().equals(HttpStatus.OK)) {
                    success = true;
                }
            } catch (Exception e) {
                LOGGER.error("Failed to upload attachment", e);
            }
        }
        return success;
    }