-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathupload_document.apx
57 lines (51 loc) · 2.28 KB
/
upload_document.apx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* This code snippet performs a multipart/form-data HTTP request from Apex to Docparser. */
/* Creating multipart/form-dat requests is unfortunately quite complex in Apex. */
/* If you interested in more details, please visit: https://docparser.com/blog/post-file-salesforce-apex-external-http-webservices/
/* Code generously provided by Theertha Prasad */
/* Updated on Dec 2021 by MY at SSC to handle docx. Special thanks to Adheena Jacob https://developer.salesforce.com/forums/?id=9060G000000MTZ9QAO */
// Don't forget to add remote site settings
Attachment file = [SELECT ID,Name,Body FROM Attachment WHERE Id = 'FILE_ID']; // Add id filter to get proper pdf attachment
// change the following variables according to your use-case
String apiKey = 'DP_API_KEY';
String parserId = 'DP_PARSER_ID';
String targetURL = 'https://api.docparser.com/v1/document/upload/' + parserId + '?remote_id=' + file.Id;
String boundary = 'A_RANDOM_STRING';
// header
String header = '--' + boundary + '\nContent-Disposition: form-data; name="file"; filename="' + file.Name + '"\nContent-Type: multipart/form-data;'+'\nnon-svg='+True;
String headerEncoded;
do
{
header += ' ';
headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header + '\r\n\r\n'));
}
while(headerEncoded.endsWith('='));
// body
String footer = '--' + boundary + '--';
String bodyEncoded = EncodingUtil.base64Encode(file.Body);
if (bodyEncoded.endsWith('=='))
{
bodyEncoded = bodyEncoded.substring(0, bodyEncoded.length()-2) + '0K';
}
else if(bodyEncoded.endsWith('='))
{
bodyEncoded = bodyEncoded.substring(0, bodyEncoded.length()-1) + 'N';
footer = '\n' + footer;
}
else
{
footer = '\r\n' + footer;
}
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
Blob bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
System.debug('bodyBlob.size()' + bodyBlob.size());
// send
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
req.setHeader('Authorization', 'Basic ' + apiKey);
req.setMethod('POST');
req.setEndpoint(targetURL);
req.setBodyAsBlob(bodyBlob);
req.setHeader('Content-Length', String.valueof(req.getBodyAsBlob().size()));
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug('res' + res.getBody());