Skip to content

Instantly share code, notes, and snippets.

@amitastreait
Created October 9, 2023 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitastreait/10b7241c4a8cc61ceea575b0ec3e4ff9 to your computer and use it in GitHub Desktop.
Save amitastreait/10b7241c4a8cc61ceea575b0ec3e4ff9 to your computer and use it in GitHub Desktop.
Upload file to Google Drive
public static void UploadFile(String fileName, String bodyEncoded, String contentType) {
String fileExtension = fileName.substring(fileName.indexOf('.')+1, fileName.length());
String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
String header = '\r\n--' + boundary + '\r\n';
String footer = '\r\n--' + boundary + '--';
String fileNameToUpload = fileName;//+'.'+fileExtension.trim();
String folderId = '19xl6WOmqZIfLCukX4YskGqlQIRSZDzXc';
List<String> listofFolderId = new List<String>();
listofFolderId.add(folderId.trim());
String body = header + 'Content-Type: application/json\r\n\r\n'
+'{ "title" : "' + fileNameToUpload + '",' + '"parents": [{"kind": "drive#fileLink","id": "'+folderId+'"}]'+','
+ ' "mimeType" : "' + contentType + '" }' + header + 'Content-Type: ' + contentType
+ '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + bodyEncoded + footer;
Http https = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Google_Drive'+'/upload/drive/v2/files?uploadType=multipart');
req.setHeader('Content-Type', 'multipart/mixed; boundary="' + boundary + '"');
req.setHeader('Content-length', String.valueOf(body.length()));
req.setBody(body);
req.setMethod('POST');
HttpResponse response = https.send(req);
System.debug(' response '+response.getBody() );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment