ilovepdf / ilovepdf-php

iLovePDF Rest Api - PHP Library (https://developer.ilovepdf.com)
146 stars 39 forks source link

Internal Server Error on file upload step #26

Closed parsam97 closed 3 years ago

parsam97 commented 3 years ago

Was not sure where else to post this as this may very well be a fault from my end.

I'm trying to upload files from Salesforce through Apex. Apex is already wobbly with file upload through HTTPRequest, but this post seemed to have gotten to the bottom of it.

However in that post, the OP only had one parameter in the body, the file itself, whereas ilovepdf needs the file as well as the task ID which is where I'm having the problem.

I tried many ways to assemble the request body. At first I was getting only badRequest with Empty or incorrect task, but after fiddling around with the \r\n construction within the requestbody, I started getting code 500 errors.

For your reference, this is my Apex code:

`String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
String header = '--'+boundary+'\r\n';
    + 'Content-Disposition: form-data; name="task"\n';
    + startResponse.task+'\r\n';
    + '--' + boundary;
    + '\r\nContent-Disposition: form-data; name="file"; filename="'+file_name+'";\nContent-Type: application/octet-stream';

String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
while (headerEncoded.endsWith('=')) {
    header += ' ';
    headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));}
String bodyEncoded = EncodingUtil.base64Encode(file_body);

Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());

String footer = '--'+boundary+'--';
if (last4Bytes.endsWith('==')) {
    last4Bytes = last4Bytes.substring(0,2) + '0K';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
} else if (last4Bytes.endsWith('=')) {
    last4Bytes = last4Bytes.substring(0,3) + 'N';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    footer = '\n' + footer;
} else {
    footer = '\r\n' + footer;
}

String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);

HttpRequest req = new HttpRequest();
if (headerMap != null) for (String key : headerMap.keySet()) req.setHeader(key, headerMap.get(key));
req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
req.setMethod('POST');
req.setEndpoint(url);
req.setBodyAsBlob(bodyBlob);
req.setTimeout(120000);

Http http = new Http();
HTTPResponse res = http.send(req);`
maztch commented 3 years ago

Please, send the request for the api use on the developers website: https://developer.ilovepdf.com/contact