Home Salesforce Uploading Files to Microsoft One Drive using Apex

Uploading Files to Microsoft One Drive using Apex

by Dhanik Lal Sahni
Upload Files in One drive using Apex- SalesforceCodex

Most of the time we have a requirement to store files in other cloud storage services like AWS, Microsoft One Drive, Dropbox, Google Drive, etc. This depends on clients’ requirements and probably license availability as well. Might be client has already these file server licenses so they will go with storing the file there itself.

Salesforce support integration with the above-mentioned file storage servers. This post is for integrating Salesforce with Microsoft One Drive to store files. We can do Microsoft One Drive integration using two ways

  • Salesforce Files Connect 
  • REST API Integration

In this post, we will do integration using REST API with Microsoft One Drive. Below steps are required for Microsoft One Drive integration

  1. Office 365 E3 License/User
  2. Azure Portal Configuration
  3. Apex Code for Token Generation and Upload
  4. Flow to Handle File Upload

There are multiple ways to upload files in Microsoft One Drive. We will use Microsoft Graph API to upload files. Microsoft Graph API offers a single endpoint, https://graph.microsoft.com, to provide access to rich, people-centric data and insights exposed as resources of Microsoft 365 services.

1. Office 365 E3

We need an office 365 license to use graph API for uploading files. Create an online account at office 365. If you are testing then use the free version. We will use the same account in registering with the azure portal so save your credential. For the free version, a credit card is required to verify user identity. It will deduct almost INR 2 and it is also refundable so go for registration to test the functionality.

2. Azure Portal Configuration

Now create a free testing account at azure portal. If you already have an azure portal account created and configured then skip this step.

While registration, similar steps as above are required and you have to go with Mobile and Identity verification.

Azure Portal Sign Up - SalesforceCodex
Azure Portal Sign Up

After portal signup process is created. Below configurations are required

  • App Registration
  • API Permission
  • Admin Consent
  • Certificate and Secret

a. App Registration

We have to register our Salesforce application in Azure Portal to handle file management.

To go App Registration page in Azure Portal, navigate Azure Active Directory->App registrations

Salesforce App Registration in Azure - SalesforceCodex
Salesforce App Registration in Azure

Create a new application like SalesforceCodex is created in the above picture. Add your Salesforce lightning application or community portal URL in redirect URIs in App registration. You can add multiple URI as well.

Select ‘Accounts in this organizational directory only’ for now in app registration.

Salesforce App Registration in Azure - SalesforceCodex
Salesforce App Registration in Azure

After registration, you will get application id (client id).

b. API Permission

After registering the client app, let us configure the client application to access a web API. This will be done by giving API permission to applications.

Here is navigation step :- Azure Active Directory -> App Registration->Select created App-> API permission

There are two types of API permissions.

Delegated permissions are selected by default. Delegated permissions are appropriate for client apps that access a web API as the signed-in user.

Application permissions are for service- or daemon-type applications that need to access a web API as themselves, without user interaction for sign-in or consent. We will use this permission to upload files as the consent screen should not show in salesforce.

Click Add a permission. This will open the request API dialog. Select Microsoft Graph, this will open the screen to select the type of permission. Select application permission to use admin permissions.

Select below permissions on the next screen to give file read and write access in One Drive. After selection click Add permission button on the bottom.

c. Admin Consent

The Grant admin consent for {your tenant} button allows an admin to grant admin consent to the permissions configured for that application. When we select the button, a dialog is shown requesting confirmation of consent action.

API Permission in Azure - SalesforceCodex
API Permission in Azure

After granting consent, the permissions that required admin consent are shown as having consent granted:

d. Certificate and Secret

Now we need to create secret key for secure API call.

Here is navigation step :- Azure Active Directory -> App Registration->Select created App-> Certificates and Secret

Create new secret key by specifying name and validity year.

Client Secret in Azure - Salesforcecodex

We are done with azure configuration now.

3. Apex Code for Token Generation and Upload

Let us now create apex class which will get access token and upload file in MS One Drive.

Create one custom metadata type One Drive Auth Setting to store API detail.

Field NameField API NameTypeSize
Auth Grant TypeAuthGrantType__cText255
Authorization EndpointAuthEndpoint__cText255
Client IdClientID__cText255
Client SecretClientSecret__cText255
Redirect UrlRedirectUrl__cText255
ScopeScope__cText200
Token UrlTokenUrl__cText255

Save all API information detail in this custom metadata type. These configuration will be used in below apex code OneDriveService.

Method Information of OneDriveService:

Metadata type information is populated in constructor. It can be passed form caller also using parameter injection.

createAuthURL: This method can be used to provide admin consent using lightning page. This is not required for this post.

ContentType: This will return correct content type for file.

UploadDocuments : This will get files information for that passed record and upload each file in Microsft one drive.

getAccessToken : This will get access token for API access to upload file.

uploadFile : This will call API to upload file.

This application service will be called from controller class OneDriveUploadController which will be used in the flow.

OneDriveUploadController has below methods-

UploadDocument : This method will be called from the flow. Flow will be called from the button click which is placed on the record page layout.

createAuthURL : This method will be used for admin consent.

4. Flow to Handle File Upload

Create a flow to call method OneDriveUploadController.UploadDocument. It will upload all files of respective records to MS One Drive.

After flow is created. Create an action button in record object to call this flow.

Demo Page:

References:

https://docs.microsoft.com/en-us/graph/api/resources/onedrive?view=graph-rest-1.0

https://docs.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

https://trailhead.salesforce.com/content/learn/modules/api_basics/api_basics_rest

https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

You may also like

18 comments

Rahul April 12, 2021 - 2:28 pm

hi there
thanks for the article, it’s very helpful
I have a question, What will happen if I skip step c. Admin Consent
actually, I have Azure credentials, and here already my teammates created an app but in the Admin consent required column there is value NO on each permission also Grant Admin consent for APP_NAme is disabled not able to click this button so is this required step
also 1 more question, in your code in uploadFile method you are using endpoint “users/37507af8-d918-437f-81c2-898fd8c1b259/drive/items/root:/{file}:/content'” what is this id “7507af8-d918-437f-81c2-898fd8c1b259” what should i use here
Thak You,
Rahul

Reply
Dhanik Lal Sahni April 18, 2021 - 12:17 am

Hello Rahul,

You have to use Admin consent or User delegated authorization. If we use admin consent then it will be applicable for all users.

7507af8-d918-437f-81c2-898fd8c1b259 is user id. You can retrieve using API https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http. use email for userPrincipalName.

Thank You,
Dhanik

Reply
Mohan October 15, 2021 - 3:45 am

Hello,

what is TokenUrl__c?

Reply
Dhanik Lal Sahni November 6, 2021 - 5:42 am

Hello Mohan,

Token URL is used to get access token once old token is expired. It is not used in post, as we are getting it from first call itself.

Thank You,
Dhanik

Reply
Etienne March 25, 2022 - 3:05 am

Hi,
Is there a reason why you did not use Named Credentials and Auth. Provider in Salesforce for this integration?

Reply
Dhanik Lal Sahni March 25, 2022 - 8:54 pm

No Etienne, There is no specific reason for this. If you are able to do using Named Credential and Auth Provider, then it is good to go.

Thank You,
Dhanik

Reply
Rodrigo December 12, 2022 - 11:20 pm

Hi Dhanik,

How can I send file has public? I’m trying to use the link from the image in salesforce but is private, is that way in the upload let public?

Reply
Dhanik Lal Sahni December 13, 2022 - 11:04 am

Hello Rodrigo,
Please check link https://salesforcecodex.com/salesforce/generate-public-link-for-salesforce-file/ to make file public. You can also use chatter to use files as publicly.
Let us connect on LinkedIn if, this will not work.

Thank You,
Dhanik

Reply
chen February 7, 2023 - 7:40 am

Hi Dhanik,

Is this process applicable to the salesforce apex restful interface to obtain and download onedrive files

Reply
Dhanik Lal Sahni February 7, 2023 - 9:02 pm

Yes, It is for REST API Integration in Apex.

Thank You,
Dhanik

Reply
Varun April 27, 2023 - 11:43 am

Can we do this without Azure?

Reply
Dhanik Lal Sahni April 28, 2023 - 1:13 pm

Hello Varun,
Azure is core so it will not be doable without it.

Thank You
Dhanik

Reply
Sanjeev Sharma May 30, 2023 - 11:00 pm

Hi Dhanik,

Thank you for your post, It was really helpful.
I have tried it, In my case file is copied to share point instead of One Drive, Our requirement is to copy the file to one drive.
Could you please help?

Thank You
Sanjeev

Reply
Dhanik Lal Sahni June 12, 2023 - 11:30 am

Hello Sanjeev,

Can you please share API url which you are using to upload files?

Thank You,
Dhanik

Reply
Janani January 26, 2024 - 8:38 am

Hi Dhanik,

Thanks for the post.It helped me a lot. I am trying to create a folder in onedrive and upload the document to the folder but the folderId is returned as null although the folder gets created. PFB code. Please can you help.

public class OneDriveService {
private string clientId {get;set;}
private string clientSecret {get;set;}
private string scope {get;set;}
private string grantType{get;set;}
private string tokenUrl{get;set;}
private string redirectUrl {get;set;}
private string graphUrl{get;set;}
private string authUrl{get;set;}
private string adminConsentUrl{get;set;}

private static One_Drive_Auth_Setting__mdt setting;

public OneDriveService()
{
if(setting==null)
{
setting=MetadataTypeReader.OneDriveSetting;
}
if(setting!=null)
{
clientId=setting.Client_Id__c;
clientSecret=setting.Client_Secret__c;
scope=setting.Scope__c;
grantType=setting.Auth_Grant_Type__c;
redirectUrl=setting.Redirect_Url__c;
//authUrl=setting.Authorization_Endpoint__c;
//tokenUrl=setting.Token_Url__c;
authUrl=setting.Authorization_Endpoint__c.replace(‘{tenant}’, setting.TenantId__c);
tokenUrl=setting.Token_Url__c.replace(‘{tenant}’, setting.TenantId__c);
}
}

//use when Admin Consent required using Salesforce App
public String createAuthURL() {
String key = EncodingUtil.urlEncode(clientId,’UTF-8′);
String authuri = ”;
authuri = adminConsentUrl+’?’+
‘client_id=’+key+
‘&redirect_uri=’+redirectUrl+
‘&state=12345’;
return authuri;
}

//Content Type based on Content Version
public static string ContentType(string fileType)
{
switch on fileType.toLowerCase()
{
when ‘docx’
{
return ‘application/vnd.openxmlformats-officedocument.wordprocessingml.document’;
}
when ‘csv’
{
return ‘application/vnd.ms-excel’;
}
when ‘wav’
{
return ‘audio/wav’;
}
when ‘wmv’
{
return ‘video/x-ms-wmv’;
}
when ‘mp3’
{
return ‘audio/mpeg’;
}
when ‘mp4’
{
return ‘video/mp4’;
}
when ‘png’
{
return ‘image/png’;

}
when ‘pdf’
{
return ‘application/pdf’;

}
when ‘txt’
{
return ‘text/plain’;

}
when else {
return ‘image/jpeg’;
}
}
}

//Upload Documents of passed record id
public void UploadDocuments(string recordId)
{
string accessToken=getAccessToken();
String folderId= createFolder(accessToken,recordId);
system.debug(‘folder’ +folderId);

// createFolder.get(id);
if(string.isBlank(accessToken))
{
// throw new BaseException(‘Issue in Authentication’);
}
List links=[SELECT ContentDocumentId,Visibility,LinkedEntityId FROM ContentDocumentLink where LinkedEntityId=:recordId];
Set ids=new Set();
for(ContentDocumentLink link:links)
{
ids.add(link.ContentDocumentId);
link.Visibility=’AllUsers’;
update link;
}
List versions=[SELECT VersionData,Title,ContentDocumentId,FileExtension FROM ContentVersion WHERE ContentDocumentId = :ids AND IsLatest = true ];

for(ContentVersion attach:versions)
{
try
{

//getCreateFolder(accessToken, attach.VersionData, attach.Title, attach.FileExtension);
uploadFile(folderId,attach.title,accessToken, attach.VersionData, attach.Title, attach.FileExtension);
}
catch(Exception ex)
{
//throw new BaseException(ex);
}
}
}

//Get access Token
public string getAccessToken()
{
String key = EncodingUtil.urlEncode(clientId,’UTF-8′);
String secret = EncodingUtil.urlEncode(clientSecret,’UTF-8′);
//Getting access token from google
HttpRequest req = new HttpRequest();
req.setMethod(‘POST’);
//req.setEndpoint(‘https://login.microsoftonline.com/df90518a-bb1d-4202-8191-314022d9a40a/oauth2/v2.0/token’);
req.setEndpoint(tokenUrl);
req.setHeader(‘content-type’, ‘application/x-www-form-urlencoded’);

String messageBody=’client_id=’+key+
‘&scope=https://graph.microsoft.com/.default’+
‘&client_secret=’+secret+
‘&redirect_uri=’+redirectUrl+
‘&grant_type=client_credentials’;

req.setHeader(‘Content-length’, String.valueOf(messageBody.length()));
req.setBody(messageBody);
req.setTimeout(60*1000);

Http callout = new Http();
String responseText;
HttpResponse response = callout.send(req);

system.debug(‘response:’ + response.getBody());
if(response.getStatusCode()==200)
{
responseText = response.getBody();
Map responseMap =(Map)JSON.deserializeUntyped(responseText) ;
string token=String.valueOf(responseMap.get(‘access_token’));
system.debug(‘responseMap:’ + responseMap);
return token;
}
return ”;
}
@future(callout=true)
public static void createFolder(String accessToken,String folderName) {
// Step 1: Get Access Token
// String accessToken = getAccessToken();

// Step 2: Make API Call to create folder
String encodedFolderName = EncodingUtil.urlEncode(folderName, ‘UTF-8’);

//request.setBody(‘{“name”: “‘ + folderName + ‘”, “folder”: {}, “@microsoft.graph.conflictBehavior”: “rename”}’);
String endpointUrl = ‘https://graph.microsoft.com/v1.0/users/728e7840-2ac6-49bb-97ae-7c34ed560909/drive/root/children’;
//String endpointUrl =’https://graph.microsoft.com/v1.0/users/728e7840-2ac6-49bb-97ae-7c34ed560909/drive/root:/{folder_name}:/children’;
//endpointUrl=endpointUrl.replace(‘{folder_name}’,folderName);
HttpRequest request = new HttpRequest();
request.setEndpoint(endpointUrl);
request.setMethod(‘POST’);
request.setBody(‘{“name”: “‘ + encodedFolderName + ‘”, “folder”: {}, “@microsoft.graph.conflictBehavior”: “rename”}’);
//String requestBody = ‘{“name”: “‘ + folderName + ‘”, “folder”: {}}’;
//request.setBody(requestBody);
request.setHeader(‘Authorization’, ‘Bearer ‘ + accessToken);
request.setHeader(‘Content-Type’, ‘application/json’);

try {
HttpResponse response = new Http().send(request);
Map jsonResponse = (Map) JSON.deserializeUntyped(response.getBody());
return (String) jsonResponse.get(‘id’);
} catch (Exception e) {
System.debug(‘Error creating folder: ‘ + e.getMessage());
return null;
}

}

@Future(callout=true)
public static void uploadFile( string folderId, String documentName,string accessToken,blob versionData,string title,string extn){
//File Content
// String attachmentBody = EncodingUtil.base64Encode(versionData);

String filename = title;
string contentType=ContentType(extn);

//String encodedFolderName = EncodingUtil.urlEncode(folderId, ‘UTF-8’);
// system.debug(‘folder name’ +encodedFolderName);
String encodedDocumentName = EncodingUtil.urlEncode(documentName, ‘UTF-8′);

// string endpointUrl=’https://graph.microsoft.com/v1.0/users/728e7840-2ac6-49bb-97ae-7c34ed560909/drive/items/root:/{file}:/content’;
String endpointUrl = ‘https://graph.microsoft.com/v1.0/users/728e7840-2ac6-49bb-97ae-7c34ed560909/drive/items/’ + folderId + ‘:/’ + encodedDocumentName + ‘:/content’;
//string file=EncodingUtil.URLENCODE(filename,’UTF-8′).replace(‘+’, ‘%20’);
//endpointUrl=endpointUrl.replace(‘{file}’,file+’.’+extn);

HttpRequest req = new HttpRequest();
req.setEndpoint(endpointUrl);
req.setMethod(‘PUT’);
req.setHeader(‘Authorization’,’Bearer ‘ + accessToken);
//req.setHeader(‘Authorization’,’Bearer ‘ + accessToken);
//req.setHeader(‘Content-Encoding’, ‘UTF-8’);
req.setHeader(‘Content-Type’, contentType);
req.setHeader(‘accept’, ‘application/json’);
Http http = new Http();
system.debug(‘getBody1 ‘+req);
req.setBodyAsBlob(versionData);
// req.setBody(versionData.toString());
req.setTimeout(120000);
system.debug(‘Request Body: ‘ + req.getBody());

HTTPResponse res = http.send(req);
system.debug(‘getBody2 ‘+res.getBody());
system.debug(‘Response Status Code: ‘ + res.getStatusCode());
//system.debug(‘Response Body: ‘ + res.getBody());
if(res.getStatusCode()==200)
{
system.debug(‘getBody ‘+res.getBody());
}
}
}

Reply
Dhanik Lal Sahni January 27, 2024 - 8:23 pm

Hello Janani, Let us connect to resolve your issue.

Thank You,
Dhanik

Reply
kALYAN February 29, 2024 - 1:25 pm

Hi Dhanik, What is the maximum file size that can be uploaded using this approach?

Reply
Dhanik Lal Sahni March 8, 2024 - 8:45 pm

Hello Kalyan,
If we use Apex then maximum 12MB files can be uploaded. This limitation is Apex side not at MS One Drive side.

Thank You,
Dhanik

Reply

Leave a Comment