Inserting file in Salesforce file/attachment object Using custom REST API Uses property of “ContentVersion”, “ContentDocumentLink” and “getBodyAsBlob()” in apex class post method in Salesforce | File upload to Salesforce object using custom REST API

2,734 views

Hey guys, today in this post we are going to learn about How to call an external REST API to uploading files to SFDC file/attachment object using REST call in Salesforce Apex Post Methods.

This example we are uploading files to Salesforce object using custom REST API and property of ContentVersion, ContentDocumentLink and getBodyAsBlob() in Salesforce Apex Class Post Method.

To access the external REST API, First we need to Adding the Remote Site Settings

SetupRemote Site SettingsRemote Site Name Enter the URL for the remote site

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

Files we used to upload file in Salesforce

apiIntegrationCmp.cmp Lightning Component It is used to uplod the file into salesforce object from custom REST API using apex post method in salesforce.
apiIntegrationCmpController.js JavaScript Controller File It is hold Javascript apiIntegrateAction function to call the apex class method and insert file to salesforce object.
downloadExcelApiCtrl.apxc

Apex Class Controller It is used to get the file from custom API and uploading files to SFDC using Apex post method.
Salesforce Object

Object Name:- Opportunity
Related Object’s Name:- File/Attachment

 

You can download file directly from github by Click Here.

 

 

Other related post that would you like to learn in Salesforce

 

  • Find the below steps:-

Create Lightning Component

Step 1:- Create Lightning Component : apiIntegrationCmp.cmp

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

From Developer Console ➡ File ➡ New ➡ Lightning Component

apiIntegrationCmp.cmp [Lightning Component File]

  1.    <aura:component controller="downloadExcelApiCtrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
  2. 	<aura:attribute name="oppObj" type="Opportunity" default="{'sobjectType' : 'Opportunity'}"/>
  3.     <aura:attribute name="oppMode" type="Map"/>
  4.     <aura:attribute name="oppName" type="String" default=""/>     
  5.     <aura:attribute name="response" type="Map"/>
  6.     <aura:attribute name="spinnerImg" type="boolean" default="false"/>
  7.     <div class="slds slds-p-around--medium">
  8.         <lightning:button variant="brand" label="Insert File in Salesforce" title="Insert File in Salesforce" type="Button" onclick="{!c.apiIntegrateAction}"></lightning:button>
  9.     </div>
  10.     <br/><br/>
  11.    <!--Start RelatedTopics Section-->
  12. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  13.  
  14.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  15.  
  16.             <br/><br/>
  17.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
  18.             <div style="display:block; overflow:hidden;"> 
  19.                 <div style="width: 50%; float:left; display:inline-block">
  20.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  21.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  22.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  23.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  24.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  25.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  26.                     </ul>
  27.             </div>
  28.  
  29.             <div style="width: 50%; float:left; display:inline-block">
  30.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  31.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  32.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  33.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  34.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  35.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  36.                     </ul>
  37.                 </div>
  38.                <div style="clear:both;"></div> 
  39.                <br/>
  40.                 <div class="youtubeIcon">
  41.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  42.                 </div>
  43.     </div>
  44.  
  45. </div>
  46.  
  47.   <!--End RelatedTopics Section-->
  48.  
  49.    </lightning-card> 
  50. </template>
  51.  
  52. </aura:component>

Create Component JavaScript Controller

Step 2:- Create Lightning Component : apiIntegrationCmpController.js

From Developer Console ➡ File ➡ New ➡ Lightning Component ➡ JavaScript Controller

apiIntegrationCmpController.js [JavaScript Controller]

  1.    ({
  2. 	apiIntegrateAction : function(component, event, helper) {
  3.         var recordId = component.get("v.recordId");
  4.         var oppName = component.get('v.oppName'); 
  5. 		var action = component.get("c.fileInsert");
  6.         action.setParams({
  7.             "url": 'https://test.com/fileInsert',     
  8.             "recId":recordId,
  9.             "oppNameStr": oppName,           
  10.             "fileName": oppName,
  11.           });
  12.         action.setCallback(this, function(response){
  13.             var state = response.getState(response);
  14.  
  15.             if(state == "SUCCESS"){
  16.                     component.set("v.spinnerImg",false);
  17.                     var results = response.getReturnValue();
  18.                     console.log('results ' + results);
  19.                     var getResponse = JSON.stringify(results);
  20.                     //alert(JSON.stringify(results));
  21.                       component.set("v.response", getResponse);  
  22.                      //alert(results.message);
  23.                        var toastEvent = $A.get("e.force:showToast");
  24.                         toastEvent.setParams({
  25.                             'title':'Success',
  26.                             'type':'Success',
  27.                             'message':'File Inserted Successfully in Salesforce'
  28.                         });
  29.                         toastEvent.fire();                    
  30.                 }
  31.                 else{
  32.                     var toastEvent = $A.get("e.force:showToast");
  33.                         toastEvent.setParams({
  34.                             'title':'Error',
  35.                             'type':'Error',
  36.                             'message':'Response Not Found'
  37.                         });
  38.                         toastEvent.fire(); 
  39.                 }
  40.         });
  41.         $A.enqueueAction(action);
  42. 	},
  43.  
  44. })

Create Apex Class Controller

Step 3:- Create Apex Class : downloadExcelApiCtrl.apxc

From Developer Console ➡ File ➡ New ➡ Apex Class

downloadExcelApiCtrl.apxc [Apex Class Controller]

  1.    @RestResource(urlMapping='/insertFileToSalesforce/')  
  2. global class downloadExcelApiCtrl {
  3.  
  4.     @AuraEnabled
  5.     global static void fileInsert(String recId, String oppNameStr, String url, String fileName) {        
  6.         Http h = NEW Http();   
  7.         HttpRequest req = NEW HttpRequest(); 
  8.         req.setEndpoint(url);
  9.         req.setTimeout(120000);
  10.         req.setMethod('POST');
  11.         req.setHeader('Content-Type', 'application/json;charset=UTF-8');             
  12.         req.setBody('{"oppName": "'+oppNameStr+'"}');
  13.         // Send the request, AND RETURN a response
  14.         HttpResponse res = h.send(req);
  15.         System.debug('response:--> ' + res.getBody());
  16.  
  17.         BLOB blobData = res.getBodyAsBlob();
  18.         ContentVersion cntVerson = NEW ContentVersion(); 
  19.         cntVerson.VersionData = blobData;
  20.         cntVerson.Title = fileName + '.xlsx';
  21.         cntVerson.PathOnClient = fileName + '.xlsx';        
  22.         INSERT cntVerson;
  23.         system.debug('cntVerson### ' + cntVerson);
  24.  
  25.         ContentDocumentLink contDocmnt = NEW ContentDocumentLink();
  26.         contDocmnt.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: cntVerson.Id].ContentDocumentId;
  27.         contDocmnt.LinkedEntityId = recId;
  28.         contDocmnt.ShareType = 'V';
  29.         INSERT contDocmnt;        
  30.     }    
  31.  
  32. }

uploading files to SFDC attachment object using REST call -- w3web.net

 

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

What is a custom REST API?

Custom REST APIs to build up a library of services that can be used by your mobile apps and intelligent bots.

What is REST API services?

A REST API is an application programming interface that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services.

What is REST API vs API?

REST basically is a style of web architecture that governs the behavior of clients and servers. While API is a more general set of protocols and is deployed over the software to help it interact with some other software.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment