0

I am trying to consume a Google Drive API to create a file in an ApexController.

I was successful in creating a file in the root folder without specifying a name using the code below

  http h = new Http();
  Httprequest req = new HttpRequest();
  HttpResponse res = new HttpResponse();

  req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
  req.setMethod('POST');
  req.setHeader('Content-type', 'application/pdf');
  req.setHeader('Authorization', 'Bearer ' + access_token);
  req.setBodyAsBlob(EncodingUtil.base64Decode(fileActual));
  res = h.send(req);

However, the problem arose when I wanted to POST a multipart request with JSON and the BlobObject mentioned above.

I have tried implementing other solutions from these links below with no success. http://enreeco.blogspot.com/2013/01/salesforce-apex-post-mutipartform-data.html http://www.fishofprey.com/2017/04/steps-required-to-support-posting.html

Below is my attempt to implement suggested solutions. I am receiving the file as base64 string from a Lightning Component.

 @AuraEnabled
 @future(callout=true)
 public static void createFiles(Id recordId, String fileName, String fileActual) {
      Opportunity opp =[SELECT Name, Folder_ID__c FROM Opportunity WHERE id=:recordId];
      String boundary = '===============4787986298161597892==';

      Map<String, Object> jsonData = new Map<String, Object>();
      List<String> parentFolder = new List<String>{'PARENT_FOLDER_ID'};
      jsonData.put('name', 'file_apitest');
      jsonData.put('parents', parentFolder);
      String header = '--'+boundary+'\r\nContent-Type: application/json; charset=UTF-8\r\n' + JSON.serialize(jsonData);
      //String header = '--'+boundary+'\r\nContent-Disposition: form-data; name="file_apitest"; parents=["1MnAoRlAVI2YO5bS9udf6EBc9pgKt2Nsy"]\r\nContent-Type: application/json'; 
      //String header = '--'+boundary+'\r\nContent-Type: application/json; \r\n {"name" : "file_apitest", "parents"=["1MnAoRlAVI2YO5bS9udf6EBc9pgKt2Nsy"] }\r\n;
      String footer = '\r\n--'+boundary+'--';              
      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 = fileActual;
      String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));

      Blob bodyBlob = null;
      String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
      if(last4Bytes.endsWith('='))
      {
           Blob decoded4Bytes = EncodingUtil.base64Decode(last4Bytes);
           HttpRequest tmp = new HttpRequest();
           tmp.setBodyAsBlob(decoded4Bytes);
           String last4BytesFooter = tmp.getBody()+footer;   
           bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded.substring(0,bodyEncoded.length()-4)+EncodingUtil.base64Encode(Blob.valueOf(last4BytesFooter)));
      }
      else
      {
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
      }

      HttpRequest req = new HttpRequest();
      req.setHeader('Content-Type','multipart/related; boundary='+boundary);
      req.setHeader('Authorization', 'Bearer ' + access_token);
      req.setMethod('POST');
      req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
      req.setBodyAsBlob(bodyBlob);

      Http http = new Http();
      HTTPResponse res = http.send(req);


}

I have tried multiple ways in which I have commented in the code section above. Please advise if this is not possible..or if I am making a mistake. I am open to any constructive criticism. Thank you in advance...

  • Hi John, can you tell us what the current issue (or behavior) of the latest version of your code shown above is? – David Reed Jan 19 '19 at 1:35
  • Hi David, appreciate your fast reply. I am currently getting the following error code: 400, message: Parse Error – John Jan 19 '19 at 2:26
  • @DavidReed to be more precise...when I try String header = '--'+boundary+'\r\nContent-Disposition: form-data; name="file_apitest"; parents=["1MnAoRlAVI2YO5bS9udf6EBc9pgKt2Nsy"]\r\nContent-Type: application/json'; code400. Malformed multipart body – John Jan 19 '19 at 2:44
  • John, I don't have the relevant expertise to answer this question but I imagine if you could edit those details into your question they will help someone else get you a solution. – David Reed Jan 19 '19 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.