0

I used apex code for upload image in google drive.

I tried to insert image in google drive and used following keys from google api.

 key = '742709774292-47m363l44n8nn7338ptbb9krg0dfcjv7.apps.googleusercontent.com';  
secret = 'V0DME59XKHI830jHAAApfWAI' ;  
redirect_uri = 'https://c.ap1.visual.force.com/apex/TestGoogleDrivePage'; 

After using this keys I get "Access Token" from google in response in JSON format and tried to upload image in google drive using this Access Token.

Following is part of code that I used.

Endpoint = 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media';
req.setHeader('Authorization','Bearer '+accesstoken);    
req.setHeader('Content-Type','image/jpeg');     
req.setMethod('POST');

Get Image data from visualforce page and add in request. I take attachment in "pictureString" from visualforce page.

String pictureString = EncodingUtil.base64Encode(attchName.body);

pictureString = EncodingUtil.urlEncode(pictureString, 'UTF-8');

String tiStmp=String.valueOf(System.NOW().getTime() / 1000);

String myData = 'public_id=accesstoken&timestamp='+key + secret ;

Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(myData));

String hexDigest = EncodingUtil.convertToHex(hash);

String fileString = 'data:image/jpeg;base64,';   

String finalBodyString ='public_id=accesstoken&api_key='+accesstoken+
'&timestamp='+ EncodingUtil.urlEncode(tiStmp, 'UTF8')+
'&signature='+EncodingUtil.urlEncode(hexDigest, 'UTF-8')+
'&file='+EncodingUtil.urlEncode(fileString, 'UTF-8') + pictureString.trim();  

req.setBody(finalBodyString);           

HttpResponse res = https.send(req); 

With this code image added in google drive but unable to open that image. It's something like corrupted image.

Can anyone help me to solve this problem. Any help in this issue is appreciated.

  • Please mask your key and secret and never share them in public site. – Tushar Sharma Aug 14 '15 at 14:04
  • 1
    Thanks Tushar. Its fine i did not share my original key here, this is not a correct keys. – Vml Aug 14 '15 at 14:20
  • 1
    I don't see any Salesforce specific code here, only Rest commands which you tell us are successful at inserting the document to Google drive. For that reason, I'm voting to close this as off-topic for this forum and suggest you take this to a Google Drive related forum on Stack Overflow. – crmprogdev Aug 14 '15 at 14:54
  • Can you add the code where you get the image data and add it to the request. – superfell Aug 14 '15 at 18:07
  • thanks superfell. I just update my question with code to get image data and add it to the request, please check it and let me if anything more information required from my side. – Vml Aug 17 '15 at 4:44

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.