+ Start a Discussion
Madhusudan Singh 19Madhusudan Singh 19 

Post File to SharePoint from APEX

I am using the EinsteinVision_HttpBodyPart (https://github.com/muenzpraeger/salesforce-einstein-vision-apex/blob/master/src/classes/EinsteinVision_HttpBodyPart.cls) approach to create a file in Sharepoint from Salesforce. EinsteinVision_HttpBodyPart
And consuming it in my below method, with this approach files are creating but it is corrupted.
public static void fileUploadCallout(string idStr) {        
    List<contentversion> cvList = new List<contentversion>();
    cvList = [select id, title, ContentDocumentId, FileExtension, versionData from contentversion where Id = :idStr limit 1];
    if(!cvList.isEmpty())     
    {
        string fileName = cvList[0].Id;
        if(cvList[0].FileExtension!=null && cvList[0].FileExtension!='') {
            fileName = fileName + '.' + cvList[0].FileExtension;  
        }  
        //callout ePOR service
        string contentType = EinsteinVision_HttpBodyPart.GetContentType();
        
        //  Compose the form
        string form64 = '';
        form64 += EinsteinVision_HttpBodyPart.WriteBoundary();
        form64 += EinsteinVision_HttpBodyPart.WriteBlobBodyParameter('file', EncodingUtil.base64Encode(cvList[0].versionData), fileName);
        
        blob formBlob = EncodingUtil.base64Decode(form64);
        string contentLength = string.valueOf(formBlob.size());
        
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('callout:Sharepoint/_api/web/GetFolderByServerRelativeUrl(\'/sites/SalesforceFiles/Shared%20Documents/Test1\')/Files/add(url=\''+fileName+'\',overwrite=true)');
        req.setBodyAsBlob(formBlob);
        req.setHeader('Connection', 'keep-alive');
        req.setHeader('Content-Length', contentLength);
        req.setHeader('Content-Type', contentType);
        req.setTimeout(120000);
        Http http =new Http();
        HTTPResponse res = http.send(req);
    }
}

There was one more approach I used as below, with that Files were creating but if we upload PNG file then its content was distorted and colors were fading. For PDF files few blocks themselves were removed. But at least something was visible.
 
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sharepoint/_api/web/GetFolderByServerRelativeUrl(\'/sites/SalesforceFiles/Shared%20Documents/Test\')/Files/add(url=\''+fileName+'\',overwrite=true)');
req.setBodyAsBlob(fileContent); // this is blob file content
req.setHeader('Content-Type','application/octet-stream');
req.setHeader('Content-Length', String.valueOf(req.getBodyAsBlob().size()));
req.setMethod('POST');      
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());