Zendesk file upload through Spring boot REST

324 views Asked by At

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,

Reference : https://support.zendesk.com/hc/en-us/community/posts/4588002835994-Uploaded-image-is-empty-or-corrupted?page=1#community_comment_4588190155802

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.

1

There are 1 answers

0
Dilan Alex On

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");
    }
}