• sukanta Anbu 7
  • NEWBIE
  • 30 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 11
    Replies
I am trying to create a lightning component which gets a URL from a field using SOQL. This URL is returned to the aura component which navigates to the external website in which a document is saved.
But my aura component is not invoking my apex class. Not able to figure the error. Please help in finding the error. Thanks in error.

This is my Lightning component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" 
                controller="RedirectToSP">
    
    <lightning:card title='Redirect to Sharepoint Form new' >
       <div class="slds-grid slds-m-around--small" style="width:400px;">
    <lightning:button class="slds-m-left_x-small" variant="brand" label="Sharepoint" title="Sharepoint" onclick="{!c.fetchRecord}" />
      </div>
  </lightning:card>  
</aura:component>


This is my controller
({
    fetchRecord: function(component, event, helper) {
        console.log('==3==>' + component.get("v.recordId"));
        helper.recordSearch(component, event, helper)        
    }
})


My helper
({
    recordSearch : function(component, event) {
        var recordId = component.get("v.recordId");
        var action = component.get("c.fetchRecord");
        console.log('==5==>' + recordId);
        action.SetParams({
            recordId : component.get("v.recordId")
        });
         action.setCallback(this, function(response) {
           var state = response.getState();
            if (state === "SUCCESS"){
                var urlEvent = $A.get("e.force:navigateToURL");
            console.log('Response ==60 '+response.getReturnValue());
            urlEvent.setParams({ "url": response.getReturnValue()
                               });
            urlEvent.fire();
        }
        });
    }
})

The following is my apex class
public class RedirectToSP{
 
    public static String fetchRecord (string recordId) {
        system.debug('hi');
        system.debug('id--->'+recordId);
       
      Form_Object__c logdata =[select Id, SharePoint_URL__c from Form_Object__c where Id =: recordId];
        String strAssumptionFloodOnlyUrl = logdata.SharePoint_URL__c;
        return strAssumptionFloodOnlyUrl;
    }  
}
Hi this is my Trigger :
Trigger :
trigger dmsBackup on Document_Management__c (after delete, after update, before delete, before update, before insert) {
    
    if(trigger.isBefore){
       /* if(trigger.isUpdate){
            System.debug('==before update and Delete 13');
            DMSBackupHandler.beforeDeleteAndUpdate(trigger.old, trigger.new);
        } */
        if(trigger.isDelete){
            system.debug('== before delete check');
            DMSBackupHandler.beforeDelete(trigger.old);
            
        }
        /*if(trigger.isUpdate){
            DMSBackupHandler.beforeInsert(trigger.new,trigger.old);
        }*/
        if(trigger.isInsert){
            DMSBackupHandler.beforeInsert(trigger.new);
        }
        
    }
   
 if(trigger.isAfter){
        if(trigger.isDelete){
            DMSBackupHandler.afterDeleteAndUpdate(trigger.old);
        }
    }
}
Test class for the above Trigger :
@isTest 
public class DMSBackupTest {

    @testSetup
    static void initDada(){
        List<Document_Management__c> docList = new List<Document_Management__c>();
        Document_Management__c docManage1 = new Document_Management__c(Document_Name__c='test1',Doc_type__c='Other', Folder__c='Active');
        Document_Management__c docManage2 = new Document_Management__c(Document_Name__c='test2',Doc_type__c='Other', Folder__c='Active');
        docList.add(docManage1);
        docList.add(docManage2);
        insert docList;
    }
    @isTest
    static void deleteDOcMangement(){
        List<Document_Management__c> docList =    [SELECT Id, Name, jobID__c, Folder__c FROM Document_Management__c];
        Test.startTest();    
            delete docList;
        Test.stopTest();
    }
}
This is the trigger handler:

public class DMSBackupHandler {
    
    public static void afterDeleteAndUpdate(List<Document_Management__c> listOfDMS){
        List<Deleted_Document_List__c> dmsrec = new List<Deleted_Document_List__c>();
            for(Document_Management__c toBeDeleted : listOfDMS)
            {
                system.debug('toBeDeleted' + toBeDeleted);
                Deleted_Document_List__c backup = new Deleted_Document_List__c();
                backup.DeletedAccount__c = toBeDeleted.Account__c;
          //      backup.Deleted_AccountID__c = toBeDeleted.AccountID__c;
                backup.DeletedActive_Contract__c = toBeDeleted.Active_Contract__c;
                backup.DeletedCompetitor_Contract__c = toBeDeleted.Competitor_Contract__c;
                backup.DeletedContract_LOB__c = toBeDeleted.Contract_LOB__c;
                backup.DeletedDescription__c = toBeDeleted.Description__c;
                backup.DeletedDoc_type__c = toBeDeleted.Doc_type__c;
                backup.DeletedDocument_Name__c = toBeDeleted.Name;
                backup.folders__c = 'Deleted';
                backup.Deletedid_reference__c = toBeDeleted.id_reference__c;
                backup.DeletedJobID__c = toBeDeleted.jobID__c;
                backup.DeletedKey_Words__c = toBeDeleted.Key_Words__c;
                backup.DeletedVersion__c = toBeDeleted.Version__c;
                backup.External_File_Path__c = toBeDeleted.External_File_Path__c;
                backup.Deleted_File_Uploaded__c = toBeDeleted.File_Uploaded__c;
                dmsrec.add(backup);
                system.debug('backup '+backup); 
            }
          if(dmsrec.size()>0)
            {
                insert dmsrec;
                system.debug('list'+ dmsrec);
            }
    }
  /*   public static void beforeDeleteAndUpdate(List<Document_Management__c> listOfDMS,List<Document_Management__c> newListOfDMS){
        
        Set<Id> docFolderIdSet = new Set<Id>();
        Boolean user_has_permission = false;
        List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId
                                                              FROM PermissionSetAssignment
                                                              WHERE AssigneeId = :Userinfo.getUserId()];
        
        for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
            System.debug('##psa.PermissionSet.Name' + psa.PermissionSet.Name);
            if ( psa.PermissionSet.Name.equals('DMS_Gatekeeper') ) {
                user_has_permission = true;
            }
        }
        
        for(Document_Management__c dms : listOfDMS){
            System.debug('==Coming error 47==');
            system.debug('==50'+dms.Doc_type__c);
            
            system.debug('DocFolderID==48== '+dms.Doc_Folder__c);
            system.debug('DocFolderName==49== '+dms.Doc_Folder__r.Name);
            if(user_has_permission == true && dms.Doc_type__c == 'Other'){
                docFolderIdSet.add(dms.Doc_Folder__c);
                System.debug('==Coming error 51==');
                //dms.addError('Insufficient Privilage');
            }
        }
            Set<Id> dmsSetId = new Set<Id>();
        List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c Where Id IN: docFolderIdSet];
        if(docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                if(dfolder.Name == 'Active Addendums' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Proformas'){
                   // dfolder.addError('Insufficient Privilage');
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
        if(dmsSetId != null && dmsSetId.size()>0){
            for(Document_Management__c dm : newListOfDMS){
                if(dmsSetId.contains(dm.Doc_Folder__c)){
                    dm.addError('Insufficient Privilage');
                } 
            }
        }
       
    } */
    
    
   public static void beforeDelete(List<Document_Management__c> befDelDMS){
       Set<Id> docFolderLookup = new Set<Id>();
        
        String user_has_permission = 'manager';
        List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId
                                                              FROM PermissionSetAssignment
                                                              WHERE AssigneeId = :Userinfo.getUserId()];
        
        for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
            System.debug('##psa.PermissionSet.Name' + psa.PermissionSet.Name);
            if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
                user_has_permission = 'gatekeeper';
            }
             else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
                user_has_permission = 'bidmanager';
            }
             else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
                user_has_permission = 'promanager';
            }
        }    
        if(user_has_permission == 'manager' || user_has_permission == 'bidmanager' || user_has_permission == 'promanager'){
            for(Document_Management__c FoldLookUp : befDelDMS){
              //  if(user_has_permission == true){
              system.debug('Delete DocFolderName==96== ');
                 docFolderLookup.add(FoldLookUp.Doc_Folder__c);
             //   }
            }
        }
        List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c Where Id IN: docFolderLookup];    
        
         Set<Id> dmsSetId = new Set<Id>();
       
        if(user_has_permission == 'manager' && docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                system.debug('Delete DocFolderName==107== ');
                if(dfolder.Name == 'Active Addendums' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Bids' || dfolder.Name == 'Proformas'){
                  
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
        else if(user_has_permission == 'bidmanager' && docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                system.debug('Delete DocFolderName==107== ');
                if(dfolder.Name == 'Active Addendum' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Proformas'){
                  
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
        else if(user_has_permission == 'promanager' && docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                system.debug('Delete DocFolderName==107== ');
                if(dfolder.Name == 'Active Addendum' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Bids'){
                  
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
        
        if(dmsSetId != null && dmsSetId.size()>0){
            for(Document_Management__c dmFold : befDelDMS){
                if(dmsSetId.contains(dmFold.Doc_Folder__c)){
                    dmFold.addError('Insufficient Privilage');
                } 
            }
        }
    }
   public static void beforeInsert(List<Document_Management__c> listOfDMS){
        Set<Id> docFolderLookup = new Set<Id>();
        
        String user_has_permission = 'manager';
        List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId
                                                              FROM PermissionSetAssignment
                                                              WHERE AssigneeId = :Userinfo.getUserId()];
        
        for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
            System.debug('##psa.PermissionSet.Name' + psa.PermissionSet.Name);
            if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
                user_has_permission = 'gatekeeper';
                system.debug('insert gate== 152=='+ user_has_permission);
            }
             else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
                user_has_permission = 'bidmanager';
                 system.debug('insert bid== 156=='+ user_has_permission);
            }
               else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
                user_has_permission = 'promanager';
                 system.debug('insert bid== 156=='+ user_has_permission);
            }
        }    
        
        if(user_has_permission == 'manager' || user_has_permission == 'bidmanager' || user_has_permission == 'promanager'){
            for(Document_Management__c FoldLookUp : listOfDMS){
              //  if(user_has_permission == true){
              system.debug('Delete DocFolderName==96== ');
                 docFolderLookup.add(FoldLookUp.Doc_Folder__c);
             //   }
            }
        }
      /*  else if(user_has_permission == 'gatekeeper'){
            for(Document_Management__c FoldLookUp : listOfDMS){
              //  if(user_has_permission == true){
              system.debug('Delete DocFolderName==96== ');
                 docFolderLookup.add(FoldLookUp.Doc_Folder__c); 
            }
        } */
        
        List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c Where Id IN: docFolderLookup];    
        
         Set<Id> dmsSetId = new Set<Id>();
       
        if(user_has_permission == 'manager' && docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                system.debug('Delete DocFolderName==107== ');
                if(dfolder.Name == 'Active Addendum' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Bids'){
                   // dfolder.addError('Insufficient Privilage');
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
        else if(user_has_permission == 'bidmanager' && docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                system.debug('Delete DocFolderName==107== ');
                if(dfolder.Name == 'Active Addendum' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Proformas'){
                   // dfolder.addError('Insufficient Privilage');
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
       
        else if(user_has_permission == 'promanager' && docFolderNameList.size()>0){
            for(Doc_Folder__c dfolder : docFolderNameList){
                system.debug('Delete DocFolderName==107== ');
                if(dfolder.Name == 'Active Addendums' || dfolder.Name == 'Active Contracts' || dfolder.Name == 'Archive' || dfolder.Name == 'Bids'){
                   // dfolder.addError('Insufficient Privilage');
                   dmsSetId.add(dfolder.Id);
                }
            }
        }
        
        if(dmsSetId != null && dmsSetId.size()>0){
            for(Document_Management__c dmFold : listOfDMS){
                if(dmsSetId.contains(dmFold.Doc_Folder__c)){
                    dmFold.addError('Insufficient Privilage');
                } 
            }
        }
   }
}
Test class for trigger handler :
@istest
public class DMSBackupHandlerTest {
@testSetup
    static void initDada(){
        Doc_Folder__c docFold =  new Doc_Folder__c(Folder_Name__c='testDocFold');
        insert docFold;
        
        List<Document_Management__c> docList = new List<Document_Management__c>();
        Document_Management__c docManage1 = new Document_Management__c(Document_Name__c='test1', Name = 'test1', Description__c = 'test', Key_Words__c = 'test', Version__c = 1, Doc_type__c='Other', Doc_Folder__c=docFold.Id, Contract_LOB__c = 'AC; ATG', Active_Contract__c = true, Competitor_Contract__c = true);
        Document_Management__c docManage2 = new Document_Management__c(Document_Name__c='test2', Name = 'test1', Description__c = 'test', Key_Words__c = 'test', Version__c = 1, Doc_type__c='Other', Doc_Folder__c=docFold.Id, Contract_LOB__c = 'AC; ATG', Active_Contract__c = true, Competitor_Contract__c = true);
        docList.add(docManage1);
        docList.add(docManage2);
        insert docList;
    }
     @isTest
    static void deleteDocMangement(){
        List<Document_Management__c> docList =    [SELECT Id, Name, jobID__c, Folder__c FROM Document_Management__c];
        Test.startTest();    
            delete docList;
        Test.stopTest();
    }
}
public class SingleRelatedListController {
public static boolean firstRun = true;
    
@AuraEnabled
public static List<Document_Management__c> initData(Id recordId,String folderName){
return [SELECT  Id, Name, Version__c, Date_Added__c, FROM Document_Management__c WHERE Doc_Folder__r.Name =:folderName AND File_Uploaded__c = true AND (Account__c =:  recordId OR Opportunity__c =: recordId) ORDER BY Date_Added__c DESC];
}
    
@AuraEnabled
public static String getPermissionSetAccess(){
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
        
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
 user_has_permission = 'gatekeeper';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
return user_has_permission;
}
    
@AuraEnabled
public static String FileDownload(List<String> recordIds) {     
CSRF_Token__c sectoken = [SELECT Refresh_Token__c, Session_Id__c, separationString__c FROM CSRF_Token__c];
AggregateResult[] size = [SELECT sum(File_SIze__c) sum FROM Document_Management__c WHERE id IN :recordIds];
double filesize = double.valueOf(size[0].get('sum')); 
 
if((recordIds.size()>1 && recordIds.size()<=30) && filesize <= 5000000){
Http h = new Http();
            
String url = 'https://i-dms-stg.herokuapp.com/salesforce/downloadzip/';
String separationString = sectoken.separationString__c;
            
String token = sectoken.Refresh_Token__c;
String sessionid = sectoken.Session_Id__c;  
List<Document_Management__c> dm = [SELECT id FROM Document_Management__c WHERE id IN :recordIds];
String JsonString=JSON.serialize(dm);
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json; boundary=' +separationString);
req.setHeader('X-CSRFToken', token);
req.setHeader('Cookie', 'sessionid='+sessionid +'; '+'csrftoken='+token);
req.setHeader('Referer', 'https://i-dms-stg.herokuapp.com/salesforce/login/');
req.setEndpoint(url);
req.setMethod('POST');
req.setBody(JsonString);
req.setTimeout(120000);
HttpResponse res = h.send(req);
return res.getBody();
}
else if(recordIds.size()>30 || filesize > 5000000){
String down = '';
List<Document_Management__c> dm = [SELECT Id FROM Document_Management__c WHERE Id IN :recordIds];
List<Mass_Download_List__c> downloadList = new List<Mass_Download_List__c>();
for(integer i=0; i<recordIds.size(); i++)
{
down = down+ string.valueof(recordIds[i])+',';
}
down = down.removeEnd(',');
Mass_Download_List__c downloadRec = new Mass_Download_List__c();
downloadRec.Selected_IDs__c = down;
downloadRec.Document_Count__c = recordIds.size();
mdl.Reference_Id__c+1;
insert downloadRec;
downloadList.add(downloadRec);
return null;
}
else{
Http h = new Http();
String url = 'https://i-dms-stg.herokuapp.com/salesforce/tmp-url/'+ recordIds[0]+'/';
String separationString = sectoken.separationString__c;
String token = sectoken.Refresh_Token__c;
String sessionid = sectoken.Session_Id__c;  
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json; boundary=' +separationString);
req.setHeader('X-CSRFToken', token);
req.setHeader('Cookie', 'sessionid='+sessionid +'; '+'csrftoken='+token);
req.setHeader('Referer', 'https://i-dms-stg.herokuapp.com/salesforce/login/');
req.setEndpoint(url);
req.setMethod('GET');
req.setTimeout(120000);
Http http = new Http();
HTTPResponse res = http.send(req);
return res.getBody();
}
}
    
@AuraEnabled
@future (callout=true)
public static void MassDownload(id recordId) {     
CSRF_Token__c sectoken = [SELECT Refresh_Token__c, Session_Id__c, separationString__c FROM CSRF_Token__c];
Http h = new Http();
String url = 'https://i-dms-stg.herokuapp.com/salesforce/createzip/'+ recordId+'/';
String separationString = sectoken.separationString__c;
String token = sectoken.Refresh_Token__c;
String sessionid = sectoken.Session_Id__c;  
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json; boundary=' +separationString);
req.setHeader('X-CSRFToken', token);
req.setHeader('Cookie', 'sessionid='+sessionid +'; '+'csrftoken='+token);
req.setHeader('Referer', 'https://i-dms-stg.herokuapp.com/salesforce/login/');
req.setEndpoint(url);
req.setMethod('POST');
req.setTimeout(120000);
HttpResponse res = h.send(req);
}

@AuraEnabled
public static Id updateParentRecordId(string recordId, String parentRecordId) { 
Document_Management__c dm = new Document_Management__c(Id = recordId);
dm.ParentRecordId__c = parentRecordId;
dm.Doc_type__c = 'Others';
update dm;
return recordId;
}
    
@AuraEnabled
public static Id FolderUpdate(String fileName,string recordId) {  
Document_Management__c objCust = new Document_Management__c();
try{     
Document_Management__c dm =[select id, Name, Account__c, Doc_Folder__c, Version__c, Opportunity__c, from Document_Management__c where Name =:fileName ORDER BY Version__c DESC LIMIT 1];
List<Document_Management__c> updatedInvoiceList = new List<Document_Management__c>();
objCust.Name = dm.Name;
objCust.Document_Name__c = dm.Name;
objCust.Account__c = dm.Account__c;
objCust.Version__c = dm.Version__c+1;
objCust.Opportunity__c = dm.Opportunity__c;
objCust.Doc_type__c = dm.Doc_type__c;
insert objCust;
updatedInvoiceList.add(objCust);
}
catch(Exception e){
throw new AuraHandledException('Darn it! Something went wrong: ' + e.getMessage()); 
}
return objCust.id;
}

@AuraEnabled
public static List<Document_Management__c> selectedFolderList(List<String> selectedFoldersName, Id recordId){
if(selectedFoldersName.contains('All')){
List<Document_Management__c> dmsList = [SELECT Id, Name, Version__c, Date_Added__c, Key_Words__c, Description__c, Contract_LOB__c, folders__c, Doc_type__c, Competitor_Contract__c, Active_Contract__c FROM Document_Management__c WHERE File_Uploaded__c = true AND (Account__c =:  recordId OR Opportunity__c =: recordId OR Contract__c =: recordId OR Opportunity_Tasks__c =: recordId OR Anniversary_Price_Increase__c =: recordId) ORDER BY Date_Added__c DESC];
 return dmsList;
}
else{
List<Document_Management__c> dmsList = [SELECT Id, Name, Version__c, Description__c, Date_Added__c, Key_Words__c, Contract_LOB__c, folders__c, Doc_type__c, Competitor_Contract__c, Active_Contract__c FROM Document_Management__c WHERE Doc_Folder__r.Name IN:selectedFoldersName AND File_Uploaded__c = true AND (Account__c =:  recordId OR Opportunity__c =: recordId OR Contract__c =: recordId OR Opportunity_Tasks__c =: recordId OR Anniversary_Price_Increase__c =: recordId) ORDER BY Date_Added__c DESC];
return dmsList;
}
}
@AuraEnabled
public static Boolean newDocFolder(String docName, String descptn){
Boolean isDuplicate = false;
List<String> docFolderName = new List<String>();
List<Doc_Folder__c> docFolderList = [SELECT Name FROM Doc_Folder__c];
for(Doc_Folder__c df : docFolderList){
docFolderName.add(df.Name);
}
if(docFolderName.contains(docName)){
isDuplicate = true;
return isDuplicate;
}
else{
Doc_Folder__c newFol = new Doc_Folder__c();
newFol.Name = docName;
newFol.Description__c = descptn;
insert newFol;  
return isDuplicate;
}
}
@AuraEnabled
public static Boolean hasEditPermision(String recordId){
Boolean hasViewPermission = true;
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
user_has_permission = 'gatekeeper' ;
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
Document_Management__c viewDMS = [select Id, Doc_Folder__C from Document_Management__c where Id =: recordId];
Doc_Folder__c foldPermission = [select Id, Name from Doc_Folder__c where Id =: viewDMS.Doc_Folder__c];
if(user_has_permission == 'manager' && (foldPermission.Name == 'Active Addendums' || foldPermission.Name == 'Active Contracts' || foldPermission.Name == 'Archive' || foldPermission.Name == 'Proformas' || foldPermission.Name == 'Bids')){
 hasViewPermission = false;
}
else if(user_has_permission == 'bidmanager' && (foldPermission.Name == 'Active Addendums' || foldPermission.Name == 'Active Contracts' || foldPermission.Name == 'Archive' || foldPermission.Name == 'Proformas')){
hasViewPermission = false;
}
else if(user_has_permission == 'promanager' && (foldPermission.Name == 'Active Addendums' || foldPermission.Name == 'Active Contracts' || foldPermission.Name == 'Archive' || foldPermission.Name == 'Bids')){
hasViewPermission = false;
}
return hasViewPermission;
}
    
@AuraEnabled
public static Id createDMSRecord(String recordId,String docName,  String folder){
String selectedContLOB = String.join(contLOB,',');
String myIdPrefix = String.valueOf(recordId).substring(0,3);
Document_Management__c DmsId = new Document_Management__c();
DmsId.Name = docName;
DmsId.Document_Name__c = docName;
DmsId.Doc_Folder__c = folder;
if(myIdPrefix == '001'){
DmsId.Account__c = recordId;
}
else if(myIdPrefix == '006'){
DmsId.Opportunity__c = recordId;
}
DmsId.ParentRecordId__c = recordId;
insert DmsId;
return DmsId.Id;
}
    
@AuraEnabled
public Static List<DocumentWrapper> getDocTypePickListValues(){
List<DocumentWrapper> pickListValuesList= new List<DocumentWrapper>();
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
user_has_permission = 'gatekeeper';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
Schema.DescribeFieldResult fieldResult = Document_Management__c.Doc_type__c.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
if(user_has_permission == 'gatekeeper'){
for( Schema.PicklistEntry pickListVal : ple){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}

else if (user_has_permission == 'bidmanager'){
for( Schema.PicklistEntry pickListVal : ple){
if(pickListVal.getLabel()!='Addendum' && pickListVal.getLabel()!='Contract' && pickListVal.getLabel()!='Proforma'){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}
}
}
else if (user_has_permission == 'promanager'){
for( Schema.PicklistEntry pickListVal : ple){
if(pickListVal.getLabel()!='Addendum' && pickListVal.getLabel()!='Contract' && pickListVal.getLabel()!='Bid'){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}
}
}
else{
for( Schema.PicklistEntry pickListVal : ple){
if(pickListVal.getLabel()!='Addendum' && pickListVal.getLabel()!='Contract' && pickListVal.getLabel()!='Proforma' && pickListVal.getLabel()!='Bid'){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}
}
}
return pickListValuesList;
}
@AuraEnabled
public static List<DocumentWrapper> getDocFolderNameWithId(){
List<DocumentWrapper> wraplist = new List<DocumentWrapper>();
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
        
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
user_has_permission = 'gatekeeper';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
if(user_has_permission == 'gatekeeper'){
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));
}  
}
else if (user_has_permission == 'bidmanager'){
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c WHERE Name NOT IN ('Active Addendums','Active Contracts','Proformas','Archive')];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));

}
else if (user_has_permission == 'promanager'){
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c WHERE Name NOT IN ('Active Addendums','Active Contracts','Bids','Archive')];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));

}
else{
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c WHERE Name NOT IN ('Active Addendums','Active Contracts','Bids', 'Proformas', 'Archive')];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));

}
return wraplist;
}
@InvocableMethod
public static void deleteNoFileRecord(List<Document_Management__c> recordId){
List<Document_Management__c> delRecords = [Select id from Document_Management__c where File_Uploaded__c=false];
delete delRecords;
}
  
public class MultiSelectWrapper{
@AuraEnabled
public String label;
public MultiSelectWrapper(String label){
this.label = label;
}
}
}
I have written a trigger on a custom object which will  invoke a callout written in a seperate class. The condition on which the trigger will be invoked is when there is a change in lookup field. the trigger will compare the old value and the new value and if there is a chnage the trigger will be invoked. The following is my trigger:
trigger dmsBackup on Document_Management__c (after delete, after update) {
    Boolean folderUploadCall = false;
    if(trigger.isAfter) {
        if(trigger.isDelete)
        {
            List<Deleted_DMS_Record__c> dmsrec = new List<Deleted_DMS_Record__c>();
            for(Document_Management__c toBeDeleted : trigger.old)
            {
                system.debug('toBeDeleted' + toBeDeleted);
                Deleted_DMS_Record__c backup = new Deleted_DMS_Record__c();
                backup.DeletedAccount__c = toBeDeleted.Account__c;
                //   backup.Deleted_AccountID__c = toBeDeleted.AccountID__c;
                backup.DeletedActive_Contract__c = toBeDeleted.Active_Contract__c;
                backup.DeletedCompetitor_Contract__c = toBeDeleted.Competitor_Contract__c;
                backup.DeletedContract_LOB__c = toBeDeleted.Contract_LOB__c;
                backup.DeletedDescription__c = toBeDeleted.Description__c;
                backup.DeletedDoc_type__c = toBeDeleted.Doc_type__c;
                backup.DeletedDocument_Name__c = toBeDeleted.Name;
                backup.folders__c = toBeDeleted.folders__c;
                backup.Deletedid_reference__c = toBeDeleted.id_reference__c;
                backup.DeletedJobID__c = toBeDeleted.jobID__c;
                backup.DeletedKey_Words__c = toBeDeleted.Key_Words__c;
                backup.DeletedVersion__c = toBeDeleted.Version__c;
                dmsrec.add(backup);
                system.debug('backup '+backup); 
            }
            if(dmsrec.size()>0)
            {
                insert dmsrec;
                system.debug('list'+ dmsrec);
            }
        }
        
        else if(trigger.isUpdate){
            for (Document_Management__c docfold: Trigger.new) {
                Document_Management__c oldFolder = Trigger.oldMap.get(docfold.Id);
                if (docfold.Doc_Folder__c != oldFolder.Doc_Folder__c) {
                    FolderUploadController.FolderUpdate(docfold.Id, docfold.folders__c);
                    System.debug('docfold.Id');
                }
            }
        }
        
    }
}
 The following is my apex class:
public class FolderUploadController {
@AuraEnabled
    @future (callout=true)
    public static void FolderUpdate(id recordId, String folders) {
         system.debug(recordId);
        system.debug(folders);
        Http h = new Http();

        String url = 'https://intelligent-sfdms.herokuapp.com/salesforce/movefile/'+ recordId+'/';
        String separationString = '2a8b526b-ee1e-461b-87fe-ce69c0491b04';
        String token = 'RGLYisTnzvEIRTCOJV7G3KUgnwNhYZXgKJJaOMQkgTq97RnDz6pmwuMqd9F9GBXy';
         
        Document_Management__c dm =[select id, folders__c from Document_Management__c where id=:recordId];
        system.debug('without pretty'+JSON.serialize(dm));
        String JsonString=JSON.serialize(dm);
   
             
        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type','application/json; boundary=' +separationString);
        req.setHeader('X-CSRFToken', token);
        req.setHeader('Cookie', 'sessionid=ml0as2d28qbh8du2p5687ty2oof4axcu; csrftoken=RGLYisTnzvEYTGCOJV7G3KUgnwNhYZXgKJJaOMQkgTq97RnDz6pmwuMqd9F9GBXy');
        req.setHeader('Referer', 'https://intelligent-sfdms.herokuapp.com/salesforce/login/');
        req.setHeader('recordId', recordId);
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(JsonString);
        req.setTimeout(120000);
        
        system.debug('Sentbody=' + JsonString);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
      
    }
}
The error is that the callout is made twice. Hw do I make it to execute only once. Thanks in advance
I am getting a file from lightning cmponent.I am using base64 in objreader in my helper.js to pass the file to the cntroller. I am doing a base64 encoding for multi-part file and the final body, I am doing a base64 decoding. However, this file is getting encoded 2 times cause of the encoding in js. Help me in decoding the file from js so I can do the encoding for multi-part.
The following is my helper.js file:

({
    MAX_FILE_SIZE: 4500000, //Max file size 4.5 MB 
    CHUNK_SIZE: 750000,      //Chunk Max size 750Kb 
     
    uploadHelper: function(component, event) {
        // get the selected files using aura:id [return array of files]
        var fileInput = component.find("fuploader").get("v.files");
        // get the first file using array index[0]  
        var file = fileInput[0];
        var self = this;
        // check the selected file size, if select file size greter then MAX_FILE_SIZE,
        // then show a alert msg to user,hide the loading spinner and return from function  
        if (file.size > self.MAX_FILE_SIZE) {
            component.set("v.fileName", 'Alert : File size cannot exceed ' + self.MAX_FILE_SIZE + ' bytes.\n' + ' Selected file size: ' + file.size);
            return;
        }
         
        // create a FileReader object 
        var objFileReader = new FileReader();
        // set onload function of FileReader object   
        objFileReader.onload = $A.getCallback(function() {
            var fileContent = objFileReader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
             
            fileContent = fileContent.substring(dataStart);
            // call the uploadProcess method 
            self.uploadProcess(component, file, fileContent);
        });
         
        objFileReader.readAsDataURL(file);
    },
     
    uploadProcess: function(component, file, fileContent) {
        // set a default size or startpostiton as 0 
        var startPosition = 0;
        // calculate the end size or endPostion using Math.min() function which is return the min. value   
        var endPosition = Math.min(fileContent.length, startPosition + this.CHUNK_SIZE);
         
        // start with the initial chunk, and set the attachId(last parameter)is null in begin
        this.uploadInChunk(component, file, fileContent, startPosition, endPosition, '');
    },
     
     
    uploadInChunk: function(component, file, fileContent, startPosition, endPosition, attachId) {
        // call the apex method 'SaveFile'
        var getchunk = fileContent.substring(startPosition, endPosition);
        var action = component.get("c.SaveFile");
        action.setParams({
            recordId: component.get("v.recordId"),
            fileName: file.name,
            contentType: file.type,
            file: fileContent
            
        });
         
        // set call back 
        action.setCallback(this, function(response) {
            // store the response / Attachment Id   
            returnValue = response.getReturnValue();
            var state = response.getState();
            if (state === "SUCCESS") {
                // update the start position with end postion
                startPosition = endPosition;
                endPosition = Math.min(fileContent.length, startPosition + this.CHUNK_SIZE);
                // check if the start postion is still less then end postion 
                // then call again 'uploadInChunk' method , 
                // else, diaply alert msg and hide the loading spinner
                if (startPosition < endPosition) {
                    this.uploadInChunk(component, file, fileContent, startPosition, endPosition, returnValue);
                } else {
                    alert('File has been uploaded successfully');
                }
                // handel the response errors        
            } else if (state === "INCOMPLETE") {
                alert("From server: " + response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
        // enqueue the action
        $A.enqueueAction(action);
    },
})


The following is my apex class:

public class FileUploadController {
 
    @AuraEnabled
    public static String SaveFile(String recordId, String fileName, Blob file) {
         system.debug(recordId);
        system.debug(fileName);
        Http h = new Http();
//it should automaticaly catch the file name 
     //   String fileName = 'sf.pdf';
        String url = 'https://intelligent-sfdms.herokuapp.com/salesforce/jsonupload/'+ recordId+'/';
        String separationString = '2a8b828b-ee1e-461b-87fe-ce69c0491b04';
        String token = 'RGLYisTnzvEIRTCOJV7G3KUgnwNhYZXgKJJaOMQkgTq97RnDz6pmwuMqd9F9GBXy';
        
        String header = '--'+separationString+'\r\nContent-Disposition: form-data; name="file"; filename="'+ fileName +'" \r\nContent-Type: application/octet-stream';
      
      String footer = '--'+separationString+'--';             
      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);

      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;
        
        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;
       
        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);  
      }

        system.debug('string ==>'+bodyBlob);
        system.debug('bodyBlob: ' + bodyBlob);


        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' +separationString);
        req.setHeader('X-CSRFToken', token);
        req.setHeader('Cookie', 'sessionid=ml0as2d28qbh8du2p3299ty2oof4axcu; csrftoken=RGLYisTnzvEIRTCOJV7G3KUgnwNhYZXgKJJaOMQkgTq97RnDz6pmwuMqd9F9GBXy');
        req.setHeader('Referer', 'https://intelligent-sfdms.herokuapp.com/salesforce/login/');
        req.setHeader('recordId', recordId);
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBodyAsBlob(bodyBlob);
        req.setTimeout(120000);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}


Around line 12 or 13, I have to decode the blop file that I am getting through the paraeter from UI. Please help me decoding it.
If I convert the blob file to string and then decode it, I am able to decoe it. How ever the final blob fle can only be .csv or .txt. It is not accepting any other file types like png or pdf or jpg.So I cannot convert it to string. 

 How can I decode the file from the js file so I can use the Multi-part encoding that I have did?
I am trying to get the filename from the selected file or the uploaded file dynamically rather than saving the file in a given name. Here is my aura component and jsccript file. Please help me in getting the file name dynamically from the selected file.
The following is my component:

<aura:component controller="dmsDynamicUpload" implements="force:appHostable,lightning:availableForFlowScreens,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
        <!-- Attributes and Handler -->
        <aura:attribute name="message" type="String"/>
        <aura:attribute name="recordId" type="String"/>
         <aura:attribute name="fileName" type="String"/>       
        <!-- Comp -->
        <lightning:card title='Demo Upload' iconName="standard:lead">
            <div style="height:300px; width:500px;" >

                <div class="slds-grid slds-m-around--small slds-hide" style="height:100px; width:200px;" >
                    <input aura:id="file" type="file" name="file"></input>
                </div>
                <hr/>
                <div class="slds-grid slds-m-around--small" style="width:400px;">
                    <lightning:button class="upload slds-col--padded slds-size--1-of-1 slds-p-vertical_small" variant="neutral" label="Upload" onclick="{!c.click}">
                        <lightning:icon iconName="utility:touch_action" variant="inverse"/>
                    </lightning:button>
                </div>
                <div class="slds-align_absolute-center slds-grid slds-m-around--small slds-box slds-theme--default slds-hide" aura:id="previewContainer">
                    <img aura:id="imagePreview" class="imagePreview" src="{!$Resource.leadPreview}" height="500" width="450"/>
                </div>
                <br/>        
            </div>
        </lightning:card>
        
        
        <div style="border:1px solid #ccc">
            <lightning:button aura:id="submit" type="button" class="submit" onclick="{!c.submit}">Submit</lightning:button>
        </div>
        <b style="padding-top:10px;">File: {! v.fileName }</b>
        
</aura:component>

The following is my jscript file:

({
    submit : function(component, event, helper) {
        
        var fileInput  = component.find("file").getElement();
        var file = fileInput.files[0];
        console.log('file is coming==>'+file);

        var reader = new FileReader();
   
        reader.onload = function (e) {
            var fileContent = reader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
            fileContent = fileContent.substring(dataStart)
            console.log(fileContent);
            
            var fileName = component.get("v.fileName");
            var recordId = component.get("v.recordId");
            
            var action = component.get("c.POST");
            action.setParams({ file : fileContent, recordId : recordId });
             action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
        };
        reader.readAsDataURL(file);
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            mode: 'sticky',
            message: 'Success',
            messageTemplate: '{0} record created! See it {1}!',
            messageTemplateData: ['Job', {
                url: 'https://csv-file-upload.herokuapp.com/leads/' + recordId,
                label: 'here',
                }
            ]
        });
        toastEvent.fire();
    },
    click : function(component, event, helper) {
        
        var input = component.find("file").getElement();
        input.click();
        
        var action = component.get("c.createJob");
        action.setCallback(this, function(response) {
            
                var returnValue = response.getReturnValue();
                console.log(returnValue);
                
                component.set("v.recordId", returnValue[0]);
                component.set("v.fileName", returnValue[1]);
                
            });
            $A.enqueueAction(action);
        
        window.setTimeout(
            $A.getCallback(function() {
                $A.util.removeClass(component.find('previewContainer'),"slds-hide");
            }), 120000
        )
    },
})
I have a lightning component for drag and drop functionality which should invoke a post callout in apex class and the file should get saved in a external DB . However when i try to upload a file, I am getting the fllowing error.

Action failed: c:Classfileupload$controller$handleFilesChange [Cannot read property 'getElement' of undefined]
Failing descriptor: {c:Classfileupload$controller$handleFilesChange}


The following is my component

<aura:component controller="Classfileupload" implements="force:appHostable,lightning:availableForFlowScreens,force:hasRecordId,force:lightningQuickAction" access="global">
 <!-- 'parentId' Aura Attribute for store the Id for Parent Record where we are attach our file -->  
   <aura:attribute name="recordId" type="String"/>
 <!-- 'showLoadingSpinner' attribute for show/hide the uploading image and msg in aura:if-->
   <aura:attribute name="showLoadingSpinner" type="boolean" default="false" />
 <!-- 'fileName' attribute for display the selected file name -->  
   <aura:attribute name="fileName" type="String" default="No File Selected.." />
 <!-- Lightning Input with file type and on file change call the 'handleFilesChange' controller -->
    <aura:attribute name="jobID" type="String"/>
    <!-- fetches the jobID from the record -->
 
   <lightning:input aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="file" label="Upload Attachment" multiple="false"/>
   <div class="slds-text-body_small slds-text-color_error">{!v.fileName} </div>
 
 <!--use aura:if for show-hide the loading spinner image--> 
   <aura:if isTrue="{!v.showLoadingSpinner}">
      <div class="slds-text-body_small slds-text-color_error">Uploading... 
         <img src="/auraFW/resources/aura/images/spinner.gif" class="spinner-img" alt="Loading"/>'
      </div>
   </aura:if>
   
 <br/>
    <lightning:button aura:id="submit" type="button" class="submit" onclick="{!c.doSave}">Upload Attachment</lightning:button>
</aura:component>


The following is my .js file
({
    doSave: function(component, event, helper) {
        var fileInput  = component.find("file").getElement();
        var file = fileInput.files[0];
        console.log('file is coming==>'+file);

        var reader = new FileReader();
   
        reader.onload = function (e) {
            var fileContent = reader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
            fileContent = fileContent.substring(dataStart)
            console.log(fileContent);
            
            var jobID = component.get("v.jobID");
            var recordId = component.get("v.recordId");
            
            var action = component.get("c.POST");
            action.setParams({ file : fileContent, jobID : jobID });
             action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
        };
        reader.readAsDataURL(file);
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            mode: 'sticky',
            message: 'Success',
            messageTemplate: '{0} record created! See it {1}!',
            messageTemplateData: ['Job', {
                url: 'https://csv-file-upload.herokuapp.com/leads/' + jobID,
                label: 'here',
                }
            ]
        });
        toastEvent.fire();
    },
 
    handleFilesChange: function(component, event, helper) {
        
        var input = component.find("file").getElement();
        input.handleFilesChange();
        
        var action = component.get("c.createJob");
        action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log(returnValue);
                
                component.set("v.recordId", returnValue[0]);
                component.set("v.jobID", returnValue[1]);
            });
            $A.enqueueAction(action);
        
        window.setTimeout(
            $A.getCallback(function() {
                $A.util.removeClass(component.find('previewContainer'),"slds-hide");
            }), 5000
        )
    },

})


The following is my apex class

public with sharing class Classfileupload {
 
 @AuraEnabled
    public static List<String> createJob() {
        
        List<String> myList = new List<String>();
          DMS__c dms = new DMS__c(Name='Amtex Demo3',Description__c='Test',Folder__c='Active',Key_Words__c='Test');
        insert dms;
         Id recordId = dms.Id;
      
        DMS__c recdms = [SELECT id, JobID__c, id_reference__c FROM DMS__c WHERE id = :recordId];
       
        update recdms;
        
        myList.add(recordId);
        myList.add(recdms.JobID__c);
        system.debug('ID LIST: ' + myList);
        return myList;
    }
    
    @AuraEnabled
    public static String POST(Blob file, String jobID, String fileName) {
        
        Http h = new Http();
        String url = 'https://csv-file-upload.herokuapp.com/leads/' + jobID;
        String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
        String str = file.toString();
   //     String csvBody = EncodingUtil.base64Encode(csvBlob);
        // decode 
        Blob decodedBlob = EncodingUtil.base64Decode(str);
        system.debug('string ==>'+decodedBlob);
        // convert to string
        String result = decodedBlob.toString();
        
        // assemble the body payload
        String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
        //String body = EncodingUtil.base64Encode(file) + '\n';
        String body = result + '\n';
        String footer = '--' + separationString + '--';
        String bodyPayload = header + body + footer;
        system.debug('PAYLOAD: ' + bodyPayload);

        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
        
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(bodyPayload);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}

Help me figure out what mistake is in this code and how to successfully get the file saved in external DB
This is my LWC 
<template>
     <lightning-card title="" icon-name="custom:custom19">
        <lightning-file-upload
            label="Attach receipt"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={recordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>
    </lightning-card>
    <lightning-record-edit-form object-api-name="DMS__c" onsuccess={handleSuccess} onsubmit ={handleSubmit} >
        <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
        <lightning-input-field field-name='Name'></lightning-input-field>
        <lightning-input-field field-name='Version__c'></lightning-input-field>
        <lightning-input-field field-name='Key_Words__c'></lightning-input-field>
        <lightning-input-field field-name='Doc_type__c'></lightning-input-field>
        <lightning-input-field field-name='Description__c'></lightning-input-field>
        </div>
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name='Contract_LOB__c'></lightning-input-field>
            <lightning-input-field field-name='Active_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Competitor_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Folder__c'></lightning-input-field>
         </div>
        </div>
        <div class="slds-clearfix">
            <div class="slds-align_absolute-center">
        <lightning-button class="slds-m-top_small" type="submit" label="Upload"  onclick={showSuccessToast}></lightning-button>
        <lightning-button class="slds-m-top_small" label="Cancel" onclick={allowReset}></lightning-button>
        </div>
    </div>
    </lightning-record-edit-form>
</template>

Thefollowing is my .js file
import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import POST from '@salesforce/apex/docUpload.POST';  
export default class Final extends LightningElement {
    @api recordId;
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
          var Name = component.get("v.Name");
            var Doc_type__c = component.get("v.Doc_type__c");
            var Active_Contract__c = component.get("v.Active_Contract__c");
            var Competitor_Contract__c = component.get("v.Competitor_Contract__c");
            var Version__c = component.get("v.Version__c");
            var Key_Words__c = component.get("v.Key_Words__c");
            var Folder__c = component.get("v.Folder__c");
            var action = component.get("c.POST");
            action.setParams({ file : uploadedFiles, Name : Name, Doc_type__c : Doc_type__c, Active_Contract__c : Active_Contract__c, Competitor_Contract__c : Competitor_Contract__c, Version__c : Version__c, Key_Words__c : Key_Words__c, Folder__c : Folder__c });
            action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                    variant: 'success',
                }),
            );
    }
       
    handleSuccess(event) {
        console.log('onsuccess event ',event.detail.id)
        
    }
    handleSubmit(event) {
        console.log('onsubmit event Newcomp'+ event.detail.fields);
       
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    allowReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}
my apex post callout is given
public with sharing class docUpload {
    
    public String resBody {get; set;}          
        @AuraEnabled
        public static String POST(Blob file, String Name, String Doc_type__c, String Active_Contract__c, String Competitor_Contract__c, String Version__c, String Key_Words__c, String Folder__c) {
            
            Http h = new Http();
    //    String fileName = 'leads.csv';
            String url = 'https://csv-file-upload.herokuapp.com/leads/' + recordId;
            String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
            String str = file.toString();
       //     String csvBody = EncodingUtil.base64Encode(csvBlob);
            // decode 
            Blob decodedBlob = EncodingUtil.base64Decode(str);
            system.debug('string ==>'+decodedBlob);
            // convert to string
            String result = decodedBlob.toString();
            
            // assemble the body payload
            String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
            //String body = EncodingUtil.base64Encode(file) + '\n';
            String body = result + '\n';
            String footer = '--' + separationString + '--';
            String bodyPayload = header + body + footer;
            system.debug('PAYLOAD: ' + bodyPayload);
    
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
            
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setBody(bodyPayload);
            system.debug('REQUEST: ' + req);
    
            // Send the request, and return a response
            HttpResponse res = h.send(req);
            System.debug(res.getBody());
            return res.getBody();
        }
}

 
public class leadUploadCtrl {
    
    @AuraEnabled
    public static String POST(Blob file, String jobID) {
        
        Http h = new Http();
        String fileName = 'accounts.csv';
        String url = 'https://csv-file-upload.herokuapp.com/leads/' + jobID;
        String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
        String str = file.toString();
        // decode 
        Blob decodedBlob = EncodingUtil.base64Decode(str);
        // convert to string
        String result = decodedBlob.toString();
        
        // assemble the body payload
        String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
        //String body = EncodingUtil.base64Encode(file) + '\n';
        String body = result + '\n';
        String footer = '--' + separationString + '--';
        String bodyPayload = header + body + footer;
        system.debug('PAYLOAD: ' + bodyPayload);

        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(bodyPayload);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}

In anonymous window i tried to invoke the code as follows:
leadUploadCtrl.POST();
This is my LWC 
<template>
     <lightning-card title="" icon-name="custom:custom19">
        <lightning-file-upload
            label="Attach receipt"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={recordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>
    </lightning-card>
    <lightning-record-edit-form object-api-name="DMS__c" onsuccess={handleSuccess} onsubmit ={handleSubmit} >
        <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
        <lightning-input-field field-name='Name'></lightning-input-field>
        <lightning-input-field field-name='Version__c'></lightning-input-field>
        <lightning-input-field field-name='Key_Words__c'></lightning-input-field>
        <lightning-input-field field-name='Doc_type__c'></lightning-input-field>
        <lightning-input-field field-name='Description__c'></lightning-input-field>
        </div>
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name='Contract_LOB__c'></lightning-input-field>
            <lightning-input-field field-name='Active_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Competitor_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Folder__c'></lightning-input-field>
         </div>
        </div>
        <div class="slds-clearfix">
            <div class="slds-align_absolute-center">
        <lightning-button class="slds-m-top_small" type="submit" label="Upload"  onclick={showSuccessToast}></lightning-button>
        <lightning-button class="slds-m-top_small" label="Cancel" onclick={allowReset}></lightning-button>
        </div>
    </div>
    </lightning-record-edit-form>
</template>

Thefollowing is my .js file
import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import POST from '@salesforce/apex/docUpload.POST';  
export default class Final extends LightningElement {
    @api recordId;
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
          var Name = component.get("v.Name");
            var Doc_type__c = component.get("v.Doc_type__c");
            var Active_Contract__c = component.get("v.Active_Contract__c");
            var Competitor_Contract__c = component.get("v.Competitor_Contract__c");
            var Version__c = component.get("v.Version__c");
            var Key_Words__c = component.get("v.Key_Words__c");
            var Folder__c = component.get("v.Folder__c");
            var action = component.get("c.POST");
            action.setParams({ file : uploadedFiles, Name : Name, Doc_type__c : Doc_type__c, Active_Contract__c : Active_Contract__c, Competitor_Contract__c : Competitor_Contract__c, Version__c : Version__c, Key_Words__c : Key_Words__c, Folder__c : Folder__c });
            action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                    variant: 'success',
                }),
            );
    }
       
    handleSuccess(event) {
        console.log('onsuccess event ',event.detail.id)
        
    }
    handleSubmit(event) {
        console.log('onsubmit event Newcomp'+ event.detail.fields);
       
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    allowReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}
my apex post callout is given
public with sharing class docUpload {
    
    public String resBody {get; set;}          
        @AuraEnabled
        public static String POST(Blob file, String Name, String Doc_type__c, String Active_Contract__c, String Competitor_Contract__c, String Version__c, String Key_Words__c, String Folder__c) {
            
            Http h = new Http();
    //    String fileName = 'leads.csv';
            String url = 'https://csv-file-upload.herokuapp.com/leads/' + recordId;
            String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
            String str = file.toString();
       //     String csvBody = EncodingUtil.base64Encode(csvBlob);
            // decode 
            Blob decodedBlob = EncodingUtil.base64Decode(str);
            system.debug('string ==>'+decodedBlob);
            // convert to string
            String result = decodedBlob.toString();
            
            // assemble the body payload
            String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
            //String body = EncodingUtil.base64Encode(file) + '\n';
            String body = result + '\n';
            String footer = '--' + separationString + '--';
            String bodyPayload = header + body + footer;
            system.debug('PAYLOAD: ' + bodyPayload);
    
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
            
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setBody(bodyPayload);
            system.debug('REQUEST: ' + req);
    
            // Send the request, and return a response
            HttpResponse res = h.send(req);
            System.debug(res.getBody());
            return res.getBody();
        }
}

 
I am trying to create a lightning component which gets a URL from a field using SOQL. This URL is returned to the aura component which navigates to the external website in which a document is saved.
But my aura component is not invoking my apex class. Not able to figure the error. Please help in finding the error. Thanks in error.

This is my Lightning component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" 
                controller="RedirectToSP">
    
    <lightning:card title='Redirect to Sharepoint Form new' >
       <div class="slds-grid slds-m-around--small" style="width:400px;">
    <lightning:button class="slds-m-left_x-small" variant="brand" label="Sharepoint" title="Sharepoint" onclick="{!c.fetchRecord}" />
      </div>
  </lightning:card>  
</aura:component>


This is my controller
({
    fetchRecord: function(component, event, helper) {
        console.log('==3==>' + component.get("v.recordId"));
        helper.recordSearch(component, event, helper)        
    }
})


My helper
({
    recordSearch : function(component, event) {
        var recordId = component.get("v.recordId");
        var action = component.get("c.fetchRecord");
        console.log('==5==>' + recordId);
        action.SetParams({
            recordId : component.get("v.recordId")
        });
         action.setCallback(this, function(response) {
           var state = response.getState();
            if (state === "SUCCESS"){
                var urlEvent = $A.get("e.force:navigateToURL");
            console.log('Response ==60 '+response.getReturnValue());
            urlEvent.setParams({ "url": response.getReturnValue()
                               });
            urlEvent.fire();
        }
        });
    }
})

The following is my apex class
public class RedirectToSP{
 
    public static String fetchRecord (string recordId) {
        system.debug('hi');
        system.debug('id--->'+recordId);
       
      Form_Object__c logdata =[select Id, SharePoint_URL__c from Form_Object__c where Id =: recordId];
        String strAssumptionFloodOnlyUrl = logdata.SharePoint_URL__c;
        return strAssumptionFloodOnlyUrl;
    }  
}
public class SingleRelatedListController {
public static boolean firstRun = true;
    
@AuraEnabled
public static List<Document_Management__c> initData(Id recordId,String folderName){
return [SELECT  Id, Name, Version__c, Date_Added__c, FROM Document_Management__c WHERE Doc_Folder__r.Name =:folderName AND File_Uploaded__c = true AND (Account__c =:  recordId OR Opportunity__c =: recordId) ORDER BY Date_Added__c DESC];
}
    
@AuraEnabled
public static String getPermissionSetAccess(){
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
        
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
 user_has_permission = 'gatekeeper';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
return user_has_permission;
}
    
@AuraEnabled
public static String FileDownload(List<String> recordIds) {     
CSRF_Token__c sectoken = [SELECT Refresh_Token__c, Session_Id__c, separationString__c FROM CSRF_Token__c];
AggregateResult[] size = [SELECT sum(File_SIze__c) sum FROM Document_Management__c WHERE id IN :recordIds];
double filesize = double.valueOf(size[0].get('sum')); 
 
if((recordIds.size()>1 && recordIds.size()<=30) && filesize <= 5000000){
Http h = new Http();
            
String url = 'https://i-dms-stg.herokuapp.com/salesforce/downloadzip/';
String separationString = sectoken.separationString__c;
            
String token = sectoken.Refresh_Token__c;
String sessionid = sectoken.Session_Id__c;  
List<Document_Management__c> dm = [SELECT id FROM Document_Management__c WHERE id IN :recordIds];
String JsonString=JSON.serialize(dm);
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json; boundary=' +separationString);
req.setHeader('X-CSRFToken', token);
req.setHeader('Cookie', 'sessionid='+sessionid +'; '+'csrftoken='+token);
req.setHeader('Referer', 'https://i-dms-stg.herokuapp.com/salesforce/login/');
req.setEndpoint(url);
req.setMethod('POST');
req.setBody(JsonString);
req.setTimeout(120000);
HttpResponse res = h.send(req);
return res.getBody();
}
else if(recordIds.size()>30 || filesize > 5000000){
String down = '';
List<Document_Management__c> dm = [SELECT Id FROM Document_Management__c WHERE Id IN :recordIds];
List<Mass_Download_List__c> downloadList = new List<Mass_Download_List__c>();
for(integer i=0; i<recordIds.size(); i++)
{
down = down+ string.valueof(recordIds[i])+',';
}
down = down.removeEnd(',');
Mass_Download_List__c downloadRec = new Mass_Download_List__c();
downloadRec.Selected_IDs__c = down;
downloadRec.Document_Count__c = recordIds.size();
mdl.Reference_Id__c+1;
insert downloadRec;
downloadList.add(downloadRec);
return null;
}
else{
Http h = new Http();
String url = 'https://i-dms-stg.herokuapp.com/salesforce/tmp-url/'+ recordIds[0]+'/';
String separationString = sectoken.separationString__c;
String token = sectoken.Refresh_Token__c;
String sessionid = sectoken.Session_Id__c;  
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json; boundary=' +separationString);
req.setHeader('X-CSRFToken', token);
req.setHeader('Cookie', 'sessionid='+sessionid +'; '+'csrftoken='+token);
req.setHeader('Referer', 'https://i-dms-stg.herokuapp.com/salesforce/login/');
req.setEndpoint(url);
req.setMethod('GET');
req.setTimeout(120000);
Http http = new Http();
HTTPResponse res = http.send(req);
return res.getBody();
}
}
    
@AuraEnabled
@future (callout=true)
public static void MassDownload(id recordId) {     
CSRF_Token__c sectoken = [SELECT Refresh_Token__c, Session_Id__c, separationString__c FROM CSRF_Token__c];
Http h = new Http();
String url = 'https://i-dms-stg.herokuapp.com/salesforce/createzip/'+ recordId+'/';
String separationString = sectoken.separationString__c;
String token = sectoken.Refresh_Token__c;
String sessionid = sectoken.Session_Id__c;  
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json; boundary=' +separationString);
req.setHeader('X-CSRFToken', token);
req.setHeader('Cookie', 'sessionid='+sessionid +'; '+'csrftoken='+token);
req.setHeader('Referer', 'https://i-dms-stg.herokuapp.com/salesforce/login/');
req.setEndpoint(url);
req.setMethod('POST');
req.setTimeout(120000);
HttpResponse res = h.send(req);
}

@AuraEnabled
public static Id updateParentRecordId(string recordId, String parentRecordId) { 
Document_Management__c dm = new Document_Management__c(Id = recordId);
dm.ParentRecordId__c = parentRecordId;
dm.Doc_type__c = 'Others';
update dm;
return recordId;
}
    
@AuraEnabled
public static Id FolderUpdate(String fileName,string recordId) {  
Document_Management__c objCust = new Document_Management__c();
try{     
Document_Management__c dm =[select id, Name, Account__c, Doc_Folder__c, Version__c, Opportunity__c, from Document_Management__c where Name =:fileName ORDER BY Version__c DESC LIMIT 1];
List<Document_Management__c> updatedInvoiceList = new List<Document_Management__c>();
objCust.Name = dm.Name;
objCust.Document_Name__c = dm.Name;
objCust.Account__c = dm.Account__c;
objCust.Version__c = dm.Version__c+1;
objCust.Opportunity__c = dm.Opportunity__c;
objCust.Doc_type__c = dm.Doc_type__c;
insert objCust;
updatedInvoiceList.add(objCust);
}
catch(Exception e){
throw new AuraHandledException('Darn it! Something went wrong: ' + e.getMessage()); 
}
return objCust.id;
}

@AuraEnabled
public static List<Document_Management__c> selectedFolderList(List<String> selectedFoldersName, Id recordId){
if(selectedFoldersName.contains('All')){
List<Document_Management__c> dmsList = [SELECT Id, Name, Version__c, Date_Added__c, Key_Words__c, Description__c, Contract_LOB__c, folders__c, Doc_type__c, Competitor_Contract__c, Active_Contract__c FROM Document_Management__c WHERE File_Uploaded__c = true AND (Account__c =:  recordId OR Opportunity__c =: recordId OR Contract__c =: recordId OR Opportunity_Tasks__c =: recordId OR Anniversary_Price_Increase__c =: recordId) ORDER BY Date_Added__c DESC];
 return dmsList;
}
else{
List<Document_Management__c> dmsList = [SELECT Id, Name, Version__c, Description__c, Date_Added__c, Key_Words__c, Contract_LOB__c, folders__c, Doc_type__c, Competitor_Contract__c, Active_Contract__c FROM Document_Management__c WHERE Doc_Folder__r.Name IN:selectedFoldersName AND File_Uploaded__c = true AND (Account__c =:  recordId OR Opportunity__c =: recordId OR Contract__c =: recordId OR Opportunity_Tasks__c =: recordId OR Anniversary_Price_Increase__c =: recordId) ORDER BY Date_Added__c DESC];
return dmsList;
}
}
@AuraEnabled
public static Boolean newDocFolder(String docName, String descptn){
Boolean isDuplicate = false;
List<String> docFolderName = new List<String>();
List<Doc_Folder__c> docFolderList = [SELECT Name FROM Doc_Folder__c];
for(Doc_Folder__c df : docFolderList){
docFolderName.add(df.Name);
}
if(docFolderName.contains(docName)){
isDuplicate = true;
return isDuplicate;
}
else{
Doc_Folder__c newFol = new Doc_Folder__c();
newFol.Name = docName;
newFol.Description__c = descptn;
insert newFol;  
return isDuplicate;
}
}
@AuraEnabled
public static Boolean hasEditPermision(String recordId){
Boolean hasViewPermission = true;
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
user_has_permission = 'gatekeeper' ;
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
Document_Management__c viewDMS = [select Id, Doc_Folder__C from Document_Management__c where Id =: recordId];
Doc_Folder__c foldPermission = [select Id, Name from Doc_Folder__c where Id =: viewDMS.Doc_Folder__c];
if(user_has_permission == 'manager' && (foldPermission.Name == 'Active Addendums' || foldPermission.Name == 'Active Contracts' || foldPermission.Name == 'Archive' || foldPermission.Name == 'Proformas' || foldPermission.Name == 'Bids')){
 hasViewPermission = false;
}
else if(user_has_permission == 'bidmanager' && (foldPermission.Name == 'Active Addendums' || foldPermission.Name == 'Active Contracts' || foldPermission.Name == 'Archive' || foldPermission.Name == 'Proformas')){
hasViewPermission = false;
}
else if(user_has_permission == 'promanager' && (foldPermission.Name == 'Active Addendums' || foldPermission.Name == 'Active Contracts' || foldPermission.Name == 'Archive' || foldPermission.Name == 'Bids')){
hasViewPermission = false;
}
return hasViewPermission;
}
    
@AuraEnabled
public static Id createDMSRecord(String recordId,String docName,  String folder){
String selectedContLOB = String.join(contLOB,',');
String myIdPrefix = String.valueOf(recordId).substring(0,3);
Document_Management__c DmsId = new Document_Management__c();
DmsId.Name = docName;
DmsId.Document_Name__c = docName;
DmsId.Doc_Folder__c = folder;
if(myIdPrefix == '001'){
DmsId.Account__c = recordId;
}
else if(myIdPrefix == '006'){
DmsId.Opportunity__c = recordId;
}
DmsId.ParentRecordId__c = recordId;
insert DmsId;
return DmsId.Id;
}
    
@AuraEnabled
public Static List<DocumentWrapper> getDocTypePickListValues(){
List<DocumentWrapper> pickListValuesList= new List<DocumentWrapper>();
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
user_has_permission = 'gatekeeper';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
Schema.DescribeFieldResult fieldResult = Document_Management__c.Doc_type__c.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
if(user_has_permission == 'gatekeeper'){
for( Schema.PicklistEntry pickListVal : ple){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}

else if (user_has_permission == 'bidmanager'){
for( Schema.PicklistEntry pickListVal : ple){
if(pickListVal.getLabel()!='Addendum' && pickListVal.getLabel()!='Contract' && pickListVal.getLabel()!='Proforma'){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}
}
}
else if (user_has_permission == 'promanager'){
for( Schema.PicklistEntry pickListVal : ple){
if(pickListVal.getLabel()!='Addendum' && pickListVal.getLabel()!='Contract' && pickListVal.getLabel()!='Bid'){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}
}
}
else{
for( Schema.PicklistEntry pickListVal : ple){
if(pickListVal.getLabel()!='Addendum' && pickListVal.getLabel()!='Contract' && pickListVal.getLabel()!='Proforma' && pickListVal.getLabel()!='Bid'){
pickListValuesList.add(new DocumentWrapper(pickListVal.getLabel(),pickListVal.getValue()));
}
}
}
return pickListValuesList;
}
@AuraEnabled
public static List<DocumentWrapper> getDocFolderNameWithId(){
List<DocumentWrapper> wraplist = new List<DocumentWrapper>();
String user_has_permission = 'manager';
List<PermissionSetAssignment> lstcurrentUserPerSet = [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Userinfo.getUserId()];
        
for ( PermissionSetAssignment psa : lstcurrentUserPerSet ) {
if ( psa.PermissionSet.Name.equals('CRMUserPsl') ) {
user_has_permission = 'gatekeeper';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Bids') ){
user_has_permission = 'bidmanager';
}
else if (psa.PermissionSet.Name.equals('Read_Write_Del_DMS_Proforma') ){
user_has_permission = 'promanager';
}
}
if(user_has_permission == 'gatekeeper'){
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));
}  
}
else if (user_has_permission == 'bidmanager'){
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c WHERE Name NOT IN ('Active Addendums','Active Contracts','Proformas','Archive')];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));

}
else if (user_has_permission == 'promanager'){
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c WHERE Name NOT IN ('Active Addendums','Active Contracts','Bids','Archive')];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));

}
else{
List<Doc_Folder__c> docFolderNameList = [SELECT Id, Name FROM Doc_Folder__c WHERE Name NOT IN ('Active Addendums','Active Contracts','Bids', 'Proformas', 'Archive')];
for(Doc_Folder__c doc : docFolderNameList){
wraplist.add(new DocumentWrapper(doc.Name, doc.Id));

}
return wraplist;
}
@InvocableMethod
public static void deleteNoFileRecord(List<Document_Management__c> recordId){
List<Document_Management__c> delRecords = [Select id from Document_Management__c where File_Uploaded__c=false];
delete delRecords;
}
  
public class MultiSelectWrapper{
@AuraEnabled
public String label;
public MultiSelectWrapper(String label){
this.label = label;
}
}
}
I am getting a file from lightning cmponent.I am using base64 in objreader in my helper.js to pass the file to the cntroller. I am doing a base64 encoding for multi-part file and the final body, I am doing a base64 decoding. However, this file is getting encoded 2 times cause of the encoding in js. Help me in decoding the file from js so I can do the encoding for multi-part.
The following is my helper.js file:

({
    MAX_FILE_SIZE: 4500000, //Max file size 4.5 MB 
    CHUNK_SIZE: 750000,      //Chunk Max size 750Kb 
     
    uploadHelper: function(component, event) {
        // get the selected files using aura:id [return array of files]
        var fileInput = component.find("fuploader").get("v.files");
        // get the first file using array index[0]  
        var file = fileInput[0];
        var self = this;
        // check the selected file size, if select file size greter then MAX_FILE_SIZE,
        // then show a alert msg to user,hide the loading spinner and return from function  
        if (file.size > self.MAX_FILE_SIZE) {
            component.set("v.fileName", 'Alert : File size cannot exceed ' + self.MAX_FILE_SIZE + ' bytes.\n' + ' Selected file size: ' + file.size);
            return;
        }
         
        // create a FileReader object 
        var objFileReader = new FileReader();
        // set onload function of FileReader object   
        objFileReader.onload = $A.getCallback(function() {
            var fileContent = objFileReader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
             
            fileContent = fileContent.substring(dataStart);
            // call the uploadProcess method 
            self.uploadProcess(component, file, fileContent);
        });
         
        objFileReader.readAsDataURL(file);
    },
     
    uploadProcess: function(component, file, fileContent) {
        // set a default size or startpostiton as 0 
        var startPosition = 0;
        // calculate the end size or endPostion using Math.min() function which is return the min. value   
        var endPosition = Math.min(fileContent.length, startPosition + this.CHUNK_SIZE);
         
        // start with the initial chunk, and set the attachId(last parameter)is null in begin
        this.uploadInChunk(component, file, fileContent, startPosition, endPosition, '');
    },
     
     
    uploadInChunk: function(component, file, fileContent, startPosition, endPosition, attachId) {
        // call the apex method 'SaveFile'
        var getchunk = fileContent.substring(startPosition, endPosition);
        var action = component.get("c.SaveFile");
        action.setParams({
            recordId: component.get("v.recordId"),
            fileName: file.name,
            contentType: file.type,
            file: fileContent
            
        });
         
        // set call back 
        action.setCallback(this, function(response) {
            // store the response / Attachment Id   
            returnValue = response.getReturnValue();
            var state = response.getState();
            if (state === "SUCCESS") {
                // update the start position with end postion
                startPosition = endPosition;
                endPosition = Math.min(fileContent.length, startPosition + this.CHUNK_SIZE);
                // check if the start postion is still less then end postion 
                // then call again 'uploadInChunk' method , 
                // else, diaply alert msg and hide the loading spinner
                if (startPosition < endPosition) {
                    this.uploadInChunk(component, file, fileContent, startPosition, endPosition, returnValue);
                } else {
                    alert('File has been uploaded successfully');
                }
                // handel the response errors        
            } else if (state === "INCOMPLETE") {
                alert("From server: " + response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
        // enqueue the action
        $A.enqueueAction(action);
    },
})


The following is my apex class:

public class FileUploadController {
 
    @AuraEnabled
    public static String SaveFile(String recordId, String fileName, Blob file) {
         system.debug(recordId);
        system.debug(fileName);
        Http h = new Http();
//it should automaticaly catch the file name 
     //   String fileName = 'sf.pdf';
        String url = 'https://intelligent-sfdms.herokuapp.com/salesforce/jsonupload/'+ recordId+'/';
        String separationString = '2a8b828b-ee1e-461b-87fe-ce69c0491b04';
        String token = 'RGLYisTnzvEIRTCOJV7G3KUgnwNhYZXgKJJaOMQkgTq97RnDz6pmwuMqd9F9GBXy';
        
        String header = '--'+separationString+'\r\nContent-Disposition: form-data; name="file"; filename="'+ fileName +'" \r\nContent-Type: application/octet-stream';
      
      String footer = '--'+separationString+'--';             
      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);

      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;
        
        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;
       
        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);  
      }

        system.debug('string ==>'+bodyBlob);
        system.debug('bodyBlob: ' + bodyBlob);


        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' +separationString);
        req.setHeader('X-CSRFToken', token);
        req.setHeader('Cookie', 'sessionid=ml0as2d28qbh8du2p3299ty2oof4axcu; csrftoken=RGLYisTnzvEIRTCOJV7G3KUgnwNhYZXgKJJaOMQkgTq97RnDz6pmwuMqd9F9GBXy');
        req.setHeader('Referer', 'https://intelligent-sfdms.herokuapp.com/salesforce/login/');
        req.setHeader('recordId', recordId);
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBodyAsBlob(bodyBlob);
        req.setTimeout(120000);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}


Around line 12 or 13, I have to decode the blop file that I am getting through the paraeter from UI. Please help me decoding it.
If I convert the blob file to string and then decode it, I am able to decoe it. How ever the final blob fle can only be .csv or .txt. It is not accepting any other file types like png or pdf or jpg.So I cannot convert it to string. 

 How can I decode the file from the js file so I can use the Multi-part encoding that I have did?
I have a lightning component for drag and drop functionality which should invoke a post callout in apex class and the file should get saved in a external DB . However when i try to upload a file, I am getting the fllowing error.

Action failed: c:Classfileupload$controller$handleFilesChange [Cannot read property 'getElement' of undefined]
Failing descriptor: {c:Classfileupload$controller$handleFilesChange}


The following is my component

<aura:component controller="Classfileupload" implements="force:appHostable,lightning:availableForFlowScreens,force:hasRecordId,force:lightningQuickAction" access="global">
 <!-- 'parentId' Aura Attribute for store the Id for Parent Record where we are attach our file -->  
   <aura:attribute name="recordId" type="String"/>
 <!-- 'showLoadingSpinner' attribute for show/hide the uploading image and msg in aura:if-->
   <aura:attribute name="showLoadingSpinner" type="boolean" default="false" />
 <!-- 'fileName' attribute for display the selected file name -->  
   <aura:attribute name="fileName" type="String" default="No File Selected.." />
 <!-- Lightning Input with file type and on file change call the 'handleFilesChange' controller -->
    <aura:attribute name="jobID" type="String"/>
    <!-- fetches the jobID from the record -->
 
   <lightning:input aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="file" label="Upload Attachment" multiple="false"/>
   <div class="slds-text-body_small slds-text-color_error">{!v.fileName} </div>
 
 <!--use aura:if for show-hide the loading spinner image--> 
   <aura:if isTrue="{!v.showLoadingSpinner}">
      <div class="slds-text-body_small slds-text-color_error">Uploading... 
         <img src="/auraFW/resources/aura/images/spinner.gif" class="spinner-img" alt="Loading"/>'
      </div>
   </aura:if>
   
 <br/>
    <lightning:button aura:id="submit" type="button" class="submit" onclick="{!c.doSave}">Upload Attachment</lightning:button>
</aura:component>


The following is my .js file
({
    doSave: function(component, event, helper) {
        var fileInput  = component.find("file").getElement();
        var file = fileInput.files[0];
        console.log('file is coming==>'+file);

        var reader = new FileReader();
   
        reader.onload = function (e) {
            var fileContent = reader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
            fileContent = fileContent.substring(dataStart)
            console.log(fileContent);
            
            var jobID = component.get("v.jobID");
            var recordId = component.get("v.recordId");
            
            var action = component.get("c.POST");
            action.setParams({ file : fileContent, jobID : jobID });
             action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
        };
        reader.readAsDataURL(file);
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            mode: 'sticky',
            message: 'Success',
            messageTemplate: '{0} record created! See it {1}!',
            messageTemplateData: ['Job', {
                url: 'https://csv-file-upload.herokuapp.com/leads/' + jobID,
                label: 'here',
                }
            ]
        });
        toastEvent.fire();
    },
 
    handleFilesChange: function(component, event, helper) {
        
        var input = component.find("file").getElement();
        input.handleFilesChange();
        
        var action = component.get("c.createJob");
        action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log(returnValue);
                
                component.set("v.recordId", returnValue[0]);
                component.set("v.jobID", returnValue[1]);
            });
            $A.enqueueAction(action);
        
        window.setTimeout(
            $A.getCallback(function() {
                $A.util.removeClass(component.find('previewContainer'),"slds-hide");
            }), 5000
        )
    },

})


The following is my apex class

public with sharing class Classfileupload {
 
 @AuraEnabled
    public static List<String> createJob() {
        
        List<String> myList = new List<String>();
          DMS__c dms = new DMS__c(Name='Amtex Demo3',Description__c='Test',Folder__c='Active',Key_Words__c='Test');
        insert dms;
         Id recordId = dms.Id;
      
        DMS__c recdms = [SELECT id, JobID__c, id_reference__c FROM DMS__c WHERE id = :recordId];
       
        update recdms;
        
        myList.add(recordId);
        myList.add(recdms.JobID__c);
        system.debug('ID LIST: ' + myList);
        return myList;
    }
    
    @AuraEnabled
    public static String POST(Blob file, String jobID, String fileName) {
        
        Http h = new Http();
        String url = 'https://csv-file-upload.herokuapp.com/leads/' + jobID;
        String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
        String str = file.toString();
   //     String csvBody = EncodingUtil.base64Encode(csvBlob);
        // decode 
        Blob decodedBlob = EncodingUtil.base64Decode(str);
        system.debug('string ==>'+decodedBlob);
        // convert to string
        String result = decodedBlob.toString();
        
        // assemble the body payload
        String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
        //String body = EncodingUtil.base64Encode(file) + '\n';
        String body = result + '\n';
        String footer = '--' + separationString + '--';
        String bodyPayload = header + body + footer;
        system.debug('PAYLOAD: ' + bodyPayload);

        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
        
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(bodyPayload);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}

Help me figure out what mistake is in this code and how to successfully get the file saved in external DB
This is my LWC 
<template>
     <lightning-card title="" icon-name="custom:custom19">
        <lightning-file-upload
            label="Attach receipt"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={recordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>
    </lightning-card>
    <lightning-record-edit-form object-api-name="DMS__c" onsuccess={handleSuccess} onsubmit ={handleSubmit} >
        <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
        <lightning-input-field field-name='Name'></lightning-input-field>
        <lightning-input-field field-name='Version__c'></lightning-input-field>
        <lightning-input-field field-name='Key_Words__c'></lightning-input-field>
        <lightning-input-field field-name='Doc_type__c'></lightning-input-field>
        <lightning-input-field field-name='Description__c'></lightning-input-field>
        </div>
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name='Contract_LOB__c'></lightning-input-field>
            <lightning-input-field field-name='Active_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Competitor_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Folder__c'></lightning-input-field>
         </div>
        </div>
        <div class="slds-clearfix">
            <div class="slds-align_absolute-center">
        <lightning-button class="slds-m-top_small" type="submit" label="Upload"  onclick={showSuccessToast}></lightning-button>
        <lightning-button class="slds-m-top_small" label="Cancel" onclick={allowReset}></lightning-button>
        </div>
    </div>
    </lightning-record-edit-form>
</template>

Thefollowing is my .js file
import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import POST from '@salesforce/apex/docUpload.POST';  
export default class Final extends LightningElement {
    @api recordId;
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
          var Name = component.get("v.Name");
            var Doc_type__c = component.get("v.Doc_type__c");
            var Active_Contract__c = component.get("v.Active_Contract__c");
            var Competitor_Contract__c = component.get("v.Competitor_Contract__c");
            var Version__c = component.get("v.Version__c");
            var Key_Words__c = component.get("v.Key_Words__c");
            var Folder__c = component.get("v.Folder__c");
            var action = component.get("c.POST");
            action.setParams({ file : uploadedFiles, Name : Name, Doc_type__c : Doc_type__c, Active_Contract__c : Active_Contract__c, Competitor_Contract__c : Competitor_Contract__c, Version__c : Version__c, Key_Words__c : Key_Words__c, Folder__c : Folder__c });
            action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                    variant: 'success',
                }),
            );
    }
       
    handleSuccess(event) {
        console.log('onsuccess event ',event.detail.id)
        
    }
    handleSubmit(event) {
        console.log('onsubmit event Newcomp'+ event.detail.fields);
       
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    allowReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}
my apex post callout is given
public with sharing class docUpload {
    
    public String resBody {get; set;}          
        @AuraEnabled
        public static String POST(Blob file, String Name, String Doc_type__c, String Active_Contract__c, String Competitor_Contract__c, String Version__c, String Key_Words__c, String Folder__c) {
            
            Http h = new Http();
    //    String fileName = 'leads.csv';
            String url = 'https://csv-file-upload.herokuapp.com/leads/' + recordId;
            String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
            String str = file.toString();
       //     String csvBody = EncodingUtil.base64Encode(csvBlob);
            // decode 
            Blob decodedBlob = EncodingUtil.base64Decode(str);
            system.debug('string ==>'+decodedBlob);
            // convert to string
            String result = decodedBlob.toString();
            
            // assemble the body payload
            String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
            //String body = EncodingUtil.base64Encode(file) + '\n';
            String body = result + '\n';
            String footer = '--' + separationString + '--';
            String bodyPayload = header + body + footer;
            system.debug('PAYLOAD: ' + bodyPayload);
    
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
            
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setBody(bodyPayload);
            system.debug('REQUEST: ' + req);
    
            // Send the request, and return a response
            HttpResponse res = h.send(req);
            System.debug(res.getBody());
            return res.getBody();
        }
}

 
public class leadUploadCtrl {
    
    @AuraEnabled
    public static String POST(Blob file, String jobID) {
        
        Http h = new Http();
        String fileName = 'accounts.csv';
        String url = 'https://csv-file-upload.herokuapp.com/leads/' + jobID;
        String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
        String str = file.toString();
        // decode 
        Blob decodedBlob = EncodingUtil.base64Decode(str);
        // convert to string
        String result = decodedBlob.toString();
        
        // assemble the body payload
        String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
        //String body = EncodingUtil.base64Encode(file) + '\n';
        String body = result + '\n';
        String footer = '--' + separationString + '--';
        String bodyPayload = header + body + footer;
        system.debug('PAYLOAD: ' + bodyPayload);

        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(bodyPayload);
        system.debug('REQUEST: ' + req);

        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}

In anonymous window i tried to invoke the code as follows:
leadUploadCtrl.POST();