6

i am trying create a attchment in salesforce by fetching the content of a file from google drive. The file is a zip file stored in google drive. The contents are fetched and the attachment gets created without an error,but the file is not valid zip file after that.Below is the apex code:-

String body = downloadFile (file.downloadURL,accessToken);
body = EncodingUtil.base64Encode(Blob.valueof(body));  
createattchment(body,someid,'test.component');

//code block of the method that creates the attacment
public void createattchment(string data,string parentid,string path){   
     Attachment attachment = new Attachment();
     attachment.Body = EncodingUtil.base64Decode(data);
     attachment.Name = path;
     attachment.ParentId = parentid;
     insert attachment; 
}
1
  • How are you fetching the blob data from google drive? Are you using google app script? Mar 13 '18 at 15:53
5
//code block of the method that creates the attacment
 public void createattchment(string data,string parentid,string path){   
 Attachment attachment = new Attachment();
 attachment.Body = EncodingUtil.base64Decode(data);
 attachment.Name = path;
 attachment.ParentId = parentid;
 attachment.contentType='application/zip';//can we set as application/zip and try
 insert attachment; 
}

try adding contentType as application/zip

2

It appears that you're storing the binary data of the zip inside a string. This is naturally problematic, because salesforce.com can't handle binary strings (all strings are re-encoded to utf-8 automatically, as in Java). This will corrupt the data. Instead, you will probably have to retrieve the data as a blob using a PageReference. You can use PageReference.getHeaders() to specify the OAuth token, then call getContent() to retrieve the file as a blob. You can then save this blob directly into an attachment or document. The other answer, which mentions setting the content type, is also part of the total answer-- you must specify a content type or the computer won't know how to handle the contents of the file.

1
  • Thanks for providing some information which actually helped to get it working. I fetched the data as blob using getBodyAsBlob() method .Pagereference does not help . The httpresponse class has a method that returns the response as blob. Thanks again.
    – Sneha
    Nov 7 '13 at 9:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.