I got the error as heap size limit too large, I'm able to send below 2MB file by using Asynchronous method but the limits is 12MB and trying to send 12MB file to external system by using Rest Api.
Source Org
public class SendAttachmentByRestAPI {
private final String clientId = 'YYYY';
private final String clientSecret = 'XXXXX';
private final String username = 'abcd@gmail.com';
private final String password = 'Password';
public class deserializeResponse
{
public String id;
public String access_token;
}
public String getAccessToken ()
{
String reqbody = 'grant_type=password' + '&client_id='+clientId +
'&client_secret='+clientSecret + '&username='+username + '&password='+password;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
system.debug('reqbody'+reqbody);
// req.setBody(JSON.serialize(reqbody));
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
HttpResponse res = h.send(req);
deserializeResponse response = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
system.debug('@@@@access_token@@'+response );
return response.access_token;
}
@future(callout = true)
public static void sendAttachement(){
//get Access Token
SendAttachmentByRestAPI accessTk = new SendAttachmentByRestAPI();
String accessToken;
accessToken = accessTk.getAccessToken();
System.debug('accessToken==='+accessToken);
Set<Id> contentDocIds = new Set<Id>();
for (ContentDocumentLink cdl : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId IN (SELECT Id FROM Opportunity WHERE StageName = 'Closed Won')]) {
contentDocIds.add(cdl.ContentDocumentId);
}
ContentVersion cvList = [SELECT Id,VersionData,Title,FileExtension, PathOnClient,ContentDocumentID FROM ContentVersion WHERE ContentDocumentId IN :contentDocIds limit 1];
if(accessToken != Null){
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://datasirpicnat-dev-ed.my.salesforce.com/services/apexrest/getContentVersions/');
req.setMethod('POST');
String bodyEncoded = EncodingUtil.base64Encode(cvList.VersionData);
req.setBody(
JSON.serialize(new map<String, String>{
'Title' => 'abc.jpg',
'VersionData' => bodyEncoded,
'FileExtension' => '.jpg'
})
);
req.setHeader('Authorization','Bearer ' +accessToken);
req.setHeader('Content-Type','application/json');
HttpResponse res = h.send(req);
system.debug('res'+res.getBody());
list<Document_URL__c> a = [SELECT Id,Name,Document_URL__c FROM Document_URL__c limit 1];
for(Document_URL__c b : a){
b.Document_URL__c = res.getBody();
b.name = cvList.Title;
system.debug('b.Document_URL__c'+b.Document_URL__c);
update a;
system.debug('a'+a);
} }
}
}
My Trigger:
Trigger SendFile on Opportunity (after insert){
for(Opportunity a:Trigger.new) {
SendAttachmentByRestAPI.sendAttachement();
}