'Zendesk file upload through Spring boot REST
I'm trying to upload an image to the zendesk through its API, Once the file is uploaded I can get the token but files seems empty,
This is how my code looks like,
fis = new FileInputStream(file);
fis.read(contents);
byte[] encoded = Base64.encodeBase64(contents);
fis.close();
body.add("file", encoded);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
UploadResponseObject result = restTemplate.postForObject(
remoteUri + "/api/v2/uploads.json?filename=" + multipartFile.getOriginalFilename(),
new HttpEntity<>(body, headers),
UploadResponseObject.class);
I have tried with several different headers,
headers.set("Content-Disposition","form-data; name=\"attachment\"; filename=\"laptop_183544.jpg\"");
headers.add("Content-Type","image/jpeg");
headers.add("Content-Type","multipart/form-data");
headers.add("Content-Type","application/binary");
But nothing seems to be working, File is uploaded but always an 1 KB empty file.
Can someone please help me on this?
Thanks.
Solution 1:[1]
I just tried this and have an answer to this question, I just got it too complicated early. so here is the simple solution.
//make the headers as you wish
HttpHeaders headers = new HttpHeaders();
//I have not added createHeaders method here.
HttpHeaders headers = createHeaders(username+":"+password, headers);
for (MultipartFile multipartFile : attachments) {
try {
String url = remoteUri+"/api/v2/uploads.json?filename="+multipartFile.getName();
headers.add("Content-Type","application/binary");
HttpEntity httpEntity = new HttpEntity(multipartFile.getBytes(),headers);
ResponseEntity<YourResponseObject> response = restTemplate.exchange(url, HttpMethod.POST,httpEntity, YourResponseObject.class);
} catch (IOException e) {
LOG.error("Input output error while uploading the image");
} catch (Exception e) {
LOG.error("Error while uploading the image");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andronicus |