Scideas Solutions Pvt. Ltd. Apex,CRM,Customer Support,REST API,Technology Salesforce apex to send image file to 3rd party using REST API

Salesforce apex to send image file to 3rd party using REST API

0 Comments


Salesforce apex to send image file to 3rd party using REST API

//attObj is an Object of Attachment object for which values will be coming from Visualforce page.
//Attachment attObj = new attachment();

public pagereference customsave(){
String fileName = attObj.name;
Blob file_body = attObj.body;
String targetURL = system.label.ImageUploadEndPointURL; //API End point URL

String boundary = ‘—————————-741e90d31eff’;

// assemble the body payload
String header = ‘–‘+boundary+’\nContent-Disposition: form-data; name=”file”;
filename=”‘+fileName+'”;\nContent-Type: application/octet-stream’;
String footer = ‘–‘+boundary+’–‘;
String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+’\r\n\r\n’));
while(headerEncoded.endsWith(‘=’))
{
header+=’ ‘;
headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+’\r\n\r\n’));
}
String bodyEncoded = EncodingUtil.base64Encode(file_body);
Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());

if(last4Bytes.endsWith(‘==’)) {
last4Bytes = last4Bytes.substring(0,2) + ‘0K’;
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
// We have appended the \r\n to the Blob, so leave footer as it is.
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
}else if(last4Bytes.endsWith(‘=’)) {
last4Bytes = last4Bytes.substring(0,3) + ‘N’;
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
// We have appended the CR e.g. \r, still need to prepend the line feed to the footer
footer = ‘\n’ + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
} else {
// Prepend the CR LF to the footer
footer = ‘\r\n’ + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);

}

HttpRequest req = new HttpRequest();
req.setHeader(‘Content-Type’,’multipart/form-data; boundary=’+boundary);
req.setMethod(‘POST’);
req.setEndpoint(targetURL);
req.setBodyAsBlob(bodyBlob);
req.setTimeout(120000);

Http http = new Http();

HTTPResponse res = http.send(req);
System.debug(‘res.getBody()’ + res.getBody());
}

//VisualForce Page

 

1 thought on “Salesforce apex to send image file to 3rd party using REST API”

Leave a Reply

Your email address will not be published. Required fields are marked *