function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sunil PalSunil Pal 

Add salesforce document in google drive

Hi all,

 

Any ane done the integration of salesforce and google.I want to upload files from salsforce to google drive using apex code.

Please help.

 

Thanks

Arunkumar.RArunkumar.R

Hi ,

 

Here is some code about salesforce to google drive integration,

 

http://theforcetimes.wordpress.com/tag/upload-files-from-salesforce-to-google-drive/

 

 

Hope this may helpful to you...!

 

Sunil PalSunil Pal

Thanks for your reply Arun

Is there any working example except this link i have already gone through this and iam not getting my output here.

 

Thanks

 

Subhani PSubhani P

Sunil,

 

Please check the following links where you can get a couple of examples for your integration.

 

http://stackoverflow.com/questions/10764740/how-to-upload-a-file-from-salesforce-to-google-drive

 

http://cloudfindhq.com/5-tips-for-salesforce-users-who-work-with-dropbox-or-google-drive/

 

http://stackoverflow.com/questions/16973602/how-to-create-and-upload-a-file-in-google-drive-using-salesforce-apex-and-drive

 

If this post is helpful please throw Kudos.If this

post solves your problem kindly mark it as solution.

Thanks,
Subhani,
Salesforce Certified Developer,
www.mydbsync.com

Raghu 1993Raghu 1993
hi sunil is this your problem solved about file upload on drive,,,,,
even i have same problem

if u have code pls share me
 
Yogesh MiyaniYogesh Miyani
Hi Arunkumar.R,

Link is very usefull
Azhar Jamil 5Azhar Jamil 5
Hi Sunil Pal,

You need to first authenticate the credentials from the link https://console.developers.google.com/project
Follow the link for the step to create the project and credentials -- credentials https://help.salesforce.com/articleView?id=000239696&type=1

The second Step you need to create one visual force page, I have added the VF page 
<apex:page controller="GoogleDriveController">
    <style>
    .error {
    font-style: italic;
    font-size: 15px;
    font-weight: bold;
    text-align: center;
    color: green;
    }
    
    .myClass {
    color: black !important;
    background: #87ceeb !important;
    width: 300px;
    font-size: 20px !important;
    height: 35px;
    }
    </style>
    <center>
        <apex:form style="margin-top:5%;margin-left:5%;width:60%">
        <apex:pageblock >
            <apex:commandbutton styleClass="myClass" onclick="this.value = 'Authenticating....'" action="{!DriveAuth}" value="Google Drive Authentication">
            </apex:commandbutton>
            <br/>
            <br/>
            <br/>
            <br/>
            <apex:inputfile value="{!file}" contentType="{!filetype}" filename="{!filename}" />
            <br/>
            <br/>
            <br/>
            <br/>
            <apex:commandButton styleClass="myClass" onclick="this.value = 'Uploading...'" value="Upload file" action="{!UploadFile}" />
            <br/>
            <br/>
            <apex:messages styleClass="error" />
            <br/>
            </apex:pageblock>
        </apex:form>
    </center>
</apex:page>

The third step is you need to create the apex-class and assign the client id and client secret which you will get from google API credentials,
I have attached the apex-class also after following this step you will be authenticated and your file will be uploaded from salesforce to google drive.
public class GoogleDriveController {
    private String code;
    public boolean val {get;set;}
    public blob file { get;set;}
    public String filetype { get;set;}
    public String filename {get;set;}
    private string key = 'Client_id';
    private string secret = 'Client_secret';
    private string redirect_uri = 'https://teqtrailhead-dev-ed--c.ap5.visual.force.com/apex/GoogleDrivePage';
    private String accesstoken;
    private Integer expiresIn;
    private String tokentype;
    public GoogleDriveController() {
        code = ApexPages.currentPage().getParameters().get('code');
        //Get the access token once we have code
        if (code != '' && code != null) {
            System.debug(' code__ ' + code);
            AccessToken();
        }
    }

    public PageReference DriveAuth() {
        //Authenticating
        PageReference pg = new PageReference(GoogleDriveAuthUri(key, redirect_uri));
        return pg;
    }

    public String GoogleDriveAuthUri(String Clientkey, String redirect_uri) {
        String key = EncodingUtil.urlEncode(Clientkey, 'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri, 'UTF-8');
        String authuri = '';
        authuri = 'https://accounts.google.com/o/oauth2/v2/auth?'+
        'scope=https://www.googleapis.com/auth/drive&'+
        'state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
        'redirect_uri=' +uri+ 
        '&response_type=code&'+
        'client_id='+key+
        '&access_type=offline';       
        return authuri;
    }
    public void UploadFile() {
        String boundary = '----------9889464542212';
        String delimiter = '\r\n--' + boundary + '\r\n';
        String close_delim = '\r\n--' + boundary + '--';
        String bodyEncoded = EncodingUtil.base64Encode(file);
        String body = delimiter + 'Content-Type: application/json\r\n\r\n' + '{ "title" : "' + filename + '",' + ' "mimeType" : "' + filetype + '" }' + delimiter + 'Content-Type: ' + filetype + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + bodyEncoded + close_delim;
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart');
        req.setHeader('Authorization', 'Bearer ' + accessToken);
        req.setHeader('Content-Type', 'multipart/mixed; boundary="' + boundary + '"');
        req.setHeader('Content-length', String.valueOf(body.length()));
        system.debug('body.length()'+body.length());
        system.debug('body>>'+body);
        req.setBody(body);
        req.setMethod('POST');
        req.setTimeout(60 * 1000);
        HttpResponse resp = http.send(req);
        system.debug('resp'+resp);
        file = null;
        filetype = '';
        filename = '';
        
    
    }

    public void AccessToken() {
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody = 'code=' + code + '&client_id=' + key + '&client_secret=' + secret + '&redirect_uri=' + redirect_uri + '&grant_type=authorization_code';

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

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
        JSONParser parser = JSON.createParser(resp);
        system.debug('resp>>>'+resp);
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)) {
                String fieldName = parser.getText();
                parser.nextToken();
                if (fieldName == 'access_token') {
                    accesstoken = parser.getText();
                } else if (fieldName == 'expires_in') {
                   
                    expiresIn = parser.getIntegerValue();
                    
                } else if (fieldname == 'token_type') {
                    tokentype = parser.getText();
                }
            }
        }
        System.debug(' You can parse the response to get the access token ::: ' + resp);
    }
}



Feel free to ask if you need further clarification.

Mark, it as best answers if you like it.

Thanks! 
yosra Saidani 24yosra Saidani 24
hi all 
i need you help please to Create google drive Folder via Apex trigger ( one folder by opportunity ) 
thank you 
Azhar Jamil 5Azhar Jamil 5

Hey Yosra,

For that first, you need to create the project in "Google API console" and set the customer id and refresh token. Link https://console.developers.google.com/project or you need to Play around Google Playground from the refresh token.

After the project is created in Google API Console.
You need to go to Salesforce, In setup- search "Auth" and use the customer id, secret and endpoint URL etc from the console where you have set.

After that, you need to write the trigger depending on the condition as per your requirements.

For the reference, you can use this trigger.
 

trigger qualifyingstage on Lead (Before Insert, Before Update) {
    
    for(Lead a : Trigger.new){
    
    Id record_type_id = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Name_of_record_type').getRecordTypeId();

    
    string Fields_name;
    list<string> qualifyinglist= new list<string>();
   
 
    if(a.Status=='Qualifying'){
    system.debug(record_type_id);
     }
     
      if(a.Status == 'Qualifying'){
    
        if(a.Fields_name1!=null || a.Fields_name2!=null {
        
            Field_Attribute=a.Fields_name2;
            Fields_name.add(Field_Attribute);
            system.debug('Fields_name>>'+qualifyinglist);
            
            
            if(qualifyinglist.size()>0){
            Googleapiupload.uploadfiles(Fields_name, Field_Attribute);
            }
        }
    }   
  }
}
 

Then you need to create the apex class and use the "ID" that code as used in "Auth" in Salesforce.

You can use this code as the reference.
 

public class Googleapiupload {

    @future (callout=true)
	public static void uploadfiles(list<string> Field_name,string st1){
        String accessToken = Auth.AuthToken.getAccessToken('ID_of_Auth_from_salesforce', 'Open ID connect');
        system.debug(accessToken);
        Map<String, String> responseMap = Auth.AuthToken.refreshAccessToken('ID_of_Auth_from_salesforce', 'Open ID connect', accessToken);
        
        String refToken;
        for(String target : responseMap.keySet()) {            
            if(target=='AccessToken'){
                refToken = responseMap.get(target);
            }
        }
        String pjstring;
         /*String pjtId,pjtName,projdescrpName1;
         for(Id projIds:proID){  			       		
             pjtId = projIds;             
          }
          for(String oppssName:projName){
              pjtName = oppssName;
          }*/
        for(string st:Field_name){
            pjstring=st;
        }
      
        system.debug('refToken'+refToken);
        String boundary = '----------9889464542212';
        String delimiter = '\r\n--' + boundary +'\r\n';
        String close_delim = '\r\n--' + boundary + '--';
        String before='';  
        String contentOfDriveInCSV = '\r '+'\r '+'Field_name1'+':  '+st1;
      	Blob beforeblob = Blob.valueOf(before);
       String bodyEncoded = EncodingUtil.base64Encode(beforeblob);
       String filename='Sample_fileNameWithoutExtension';
       String filetype='text/csv';
  	   
       String body=delimiter+'Content-Type: application/json\r\n\r\n'+'{ "title" : "'+ filename+'",'+ ' "mimeType" : "'+ filetype+ '",' + '"parents":[{"id":"'+ 'ID_of_the_folder_where_you_need_to_save_the_data' +'"}] }'+delimiter+'Content-Type: ' + filetype + '\r\n'+'Content-Transfer-Encoding: base64\r\n'+'\r\n'+bodyEncoded+close_delim;
        
  		HttpRequest req = new HttpRequest();
		req.setMethod('POST');
		req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart');
		req.setHeader('content-type', 'text/plain');
		req.setHeader('Authorization','Bearer '+refToken);
        req.setHeader('Content-Type', 'multipart/mixed; boundary="'+boundary+'"');
		
        system.debug('body'+body);
		req.setBody(contentOfDriveInCSV);  
		req.setTimeout(60*1000);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        system.debug('res'+res);
        filetype='';
       filename='';
        
    }
}
 

Now you can then save the data from Salesforce to Google drive.

Thanks, 
Let me know if you need more details
 

Dustin BookDustin Book
Hey Azhar Jamil 5,
Realize this is an old post, but worth trying. Is there a way to upload the file from salesforce to a specific google drive folder, and then create a link in salesforce under the account to view the file?

Thanks!
Vengatesh Pandiyan 7Vengatesh Pandiyan 7
I am exactly looking for the same thing i want to upload file from salesforce to gdrive   and the file link should be available under record page  if anyone have solved this please help 
Vengatesh Pandiyan 7Vengatesh Pandiyan 7
hi dustin book did you implemented thar please share that code
 
Sherbaz KhanSherbaz Khan

@Azhar Jamil 5

THANKYOU SOOOOO MUCH.. I'm currently working on GOOGLE DRIVE INTEGRATION to UPLOAD FILE using LWC and APEX.

I was able to upload files but the CONTENT inside files was getting uploaded in base64 format (Not the Actual Data), and finally here I Saw your code and only pick one line ****Content-Transfer-Encoding: base64**** to check that if it's gonna do the trick or not.. and BOOOOOM. IT WORKED. 

I was just missing this part ****Content-Transfer-Encoding: base64**** in my whole integration, just added this line and everthing is working great.

Thankyou again.