0

I am trying to send a pdf file attached to a record of custom object to an external system. I am using ContentDocumentLink and ContentVersion to get the file in apex and make a api call. File is uploaded successfully to the external system but it doesn't open, seems like data isn't correctly uploaded.

ContentVersion file = [SELECT Id, Title, ContentSize, FileExtension, VersionData FROM ContentVersion WHERE ContentDocumentId =: [SELECT ContentDocumentid, LinkedEntityid FROM contentDocumentLink WHERE LinkedEntityid = 'axxxxxxxx78'].ContentDocumentid Limit 1];
HttpRequest request = new HttpRequest();
request.setEndpoint('https://upload.box.com/api/2.0/files/content');
request.setMethod('POST');
request.setHeader('Authorization', 'Bearer J7xxxxxxxxxxxxxxxxxxxxpn');
request.setHeader('Content-Type', 'multipart/form-data; boundary=boundary_string');

String boundary = 'boundary_string';
String body = '--' + boundary + '\r\n';
body += 'Content-Disposition: form-data; name="attributes"' + '\r\n';
body += 'Content-Type: application/json' + '\r\n\r\n';
body += '{"name":"' + file.Title + '.' + file.FileExtension+ '", "parent":{"id":"' + '2xxxxxx6' + '"}}' + '\r\n';
body += '--' + boundary + '\r\n';
body += 'Content-Disposition: form-data; name="file"; filename="' + file.Title + '"' + '\r\n';
body += 'Content-Type: application/octet-stream' + '\r\n\r\n';
body += EncodingUtil.base64Encode(file.VersionData) + '\r\n';
body += '--' + boundary + '--';
system.debug(body);
request.setBody(body);
request.setHeader('Content-Length', String.valueOf(body.length()));
Http http = new Http();
HttpResponse response = http.send(request);

if (response.getStatusCode() == 201) {
    // File upload successful (201 Created)
    System.debug('File upload successful. Response: ' + response.getBody());
} else {
    // File upload failed
    System.debug('File upload failed. Response: ' + response.getBody());
    System.debug('Response Status Code: ' + response.getStatusCode());
    System.debug('Response Headers: ' + response);
}

I think the problem is at line where I am adding body of the file in the string body. Any suggestion or correction is appreciated.

2
  • I've linked a relevant answer. Summary: the file contents in the body are used as-is, so by base-64 encoding them, you've encoded the entire file, which won't be read by the appropriate program on the other end. For example, 'Hello' becomes 'SGVsbG8=', so a text editor would show 'SGVsbG8=' and not 'Hello'. You need to encode the entire body, then decode it to a blob.
    – sfdcfox
    Commented Sep 18, 2023 at 10:40
  • Thanks @sfdcfox, it helped it! Commented Sep 18, 2023 at 11:56

0

Browse other questions tagged .