A blog about Salesforce CRM Configuration and development

Saturday, 22 September 2018

Lightning - File upload with title using "lightning:fileUpload"

Lightning File Uploader Component:  <lightning:fileUpload />

I am writing this blog post just because, I faced a problem while working with the standard file uploader component, the problem is when you upload the file using standard component there is no way to enter the file Name or Title, it automatically get the file name and updates the Title with that file name, but sometimes users want to enter the specific Name or Title in that case we can not do that with standard component.


The first thing comes to my mind to solve this problem is if anyhow I get the files details before upload then I can change the file Title with the user entered name but no luck, there is no action defined for before upload in lightning:fileUpload documentation.

But, lightning:fileUpload component provides 'onuploadfinished' (The action triggered when files have finished uploading.) action, we can call the action (Method) after the file uploading finished and can get the details of files that just uploaded, after that, we can change the Title of File based on the user entered Title.

Below are the Lightning component codes that I have created to solve the problem that I was facing.

Component:
 <aura:component controller="SimplyfyFilesCntrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >  
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
   <aura:attribute name="files" type="ContentDocument[]"/>  
   <aura:attribute name="recordId" type="string"/>  
   <aura:attribute name="accept" type="List" default="['.jpg', '.jpeg','.pdf','.csv','.xlsx']"/>  
   <aura:attribute name="multiple" type="Boolean" default="true"/>  
   <aura:attribute name="disabled" type="Boolean" default="false"/>  
   <div class="slds">  
     <div style="border-left: 1px solid rgb(221, 219, 218);  
           border-right: 1px solid rgb(221, 219, 218);  
           border-bottom: 1px solid rgb(221, 219, 218);  
           border-top: 1px solid rgb(221, 219, 218);">  
       <div class="slds-page-header" style="border-radius: 0px; border-right: 0px;border-left: 0px;border-top: 0px;  
                          box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);">  
         Files  
       </div>  
       <div class="slds-grid">  
         <div class="slds-col slds-size--5-of-12">  
           <lightning:input type="text" name="input1" label="Enter File Name" aura:id="fileName" />  
         </div>&nbsp; &nbsp;  
         <div class="slds-col slds-size---of-12">  
           <lightning:fileUpload label="" multiple="{!v.multiple}"   
                      accept="{!v.accept}" recordId="{!v.recordId}"   
                      onuploadfinished="{!c.UploadFinished}" />  
         </div>  
       </div><br/>  
       <table class="slds-table slds-table--bordered">  
         <thead>  
           <tr>  
             <th>Title</th>  
             <th>FileType</th>  
             <th>Description</th>  
           </tr>  
         </thead>  
         <tbody>  
           <aura:iteration items="{!v.files}" var="f">  
             <tr>  
               <td> <a href="" id="{!f.Id}" onclick="{!c.OpenFile}">{!f.Title}</a></td>  
               <td>{!f.FileType}</td>  
               <td>{!f.Description}</td>  
             </tr>  
           </aura:iteration>  
         </tbody>  
       </table>  
     </div>  
   </div>  
 </aura:component>  

JS Controller:
 ({  
   doInit:function(component,event,helper){  
     var action = component.get("c.getFiles");  
     action.setParams({  
       "recordId":component.get("v.recordId")  
     });      
     action.setCallback(this,function(response){  
       var state = response.getState();  
       if(state=='SUCCESS'){  
         var result = response.getReturnValue();  
         console.log('result: ' +result);  
         component.set("v.files",result);  
       }  
     });  
     $A.enqueueAction(action);  
   } ,  
   //Open File onclick event  
   OpenFile :function(component,event,helper){  
     var rec_id = event.currentTarget.id;  
     $A.get('e.lightning:openFiles').fire({ //Lightning Openfiles event  
       recordIds: [rec_id] //file id  
     });  
   },  
   UploadFinished : function(component, event, helper) {  
     var uploadedFiles = event.getParam("files");  
     var documentId = uploadedFiles[0].documentId;  
     var fileName = uploadedFiles[0].name;  
     helper.UpdateDocument(component,event,documentId);  
     var toastEvent = $A.get("e.force:showToast");  
     toastEvent.setParams({  
       "title": "Success!",  
       "message": "File "+fileName+" Uploaded successfully."  
     });  
     toastEvent.fire();  
     /* Open File after upload  
     $A.get('e.lightning:openFiles').fire({  
       recordIds: [documentId]  
     });*/  
   },  
 })  

JS Helper:
 ({  
       UpdateDocument : function(component,event,Id) {  
     var action = component.get("c.UpdateFiles");  
     var fName = component.find("fileName").get("v.value");  
     //alert('File Name'+fName);  
     action.setParams({"documentId":Id,  
              "title": fName,  
              "recordId": component.get("v.recordId")  
              });  
     action.setCallback(this,function(response){  
       var state = response.getState();  
       if(state=='SUCCESS'){  
         var result = response.getReturnValue();  
         console.log('Result Returned: ' +result);  
         component.find("fileName").set("v.value", " ");  
         component.set("v.files",result);  
       }  
     });  
     $A.enqueueAction(action);  
   },  
 })  

Apex Controller:
 public class SimplyfyFilesCntrl {  
   @AuraEnabled  
   public static List<ContentDocument> getFiles(string recordId){  
     List<ContentDocument> DocumentList = new List<ContentDocument>();  
     Set<Id> documentIds = new Set<Id>();  //store file ids
     List<ContentDocumentLink> cdl=[select id,LinkedEntityId,ContentDocumentId from ContentDocumentLink where LinkedEntityId=:recordId];  
     for(ContentDocumentLink cdLink:cdl){  
       documentIds.add(cdLink.ContentDocumentId);  // Document ids
     }      
     DocumentList = [select Id,Title,FileType,ContentSize,Description from ContentDocument where id IN: documentIds];  
     return DocumentList;  
   }  
   @AuraEnabled  
   public static List<ContentDocument> UpdateFiles(string documentId,string title,string recordId){  
     system.debug('title: ' +title);  
     ContentDocument cd = [select id,title from ContentDocument where Id=:documentId]; // Getting files from Parent record 
     cd.Title = title;  // Changing file Title with user entered title
     try{  
       update cd;  // Update ContentDocument (File)
     }  
     catch(DMLException e){  
       system.debug('Exception has occurred! ' +e.getMessage());  
     }  
      List<ContentDocument> DocumentList = new List<ContentDocument>();  
     Set<Id> documentIds = new Set<Id>();  
     List<ContentDocumentLink> cdl=[select id,LinkedEntityId,ContentDocumentId from ContentDocumentLink where LinkedEntityId=:recordId];  
     for(ContentDocumentLink cdLink:cdl){  
       documentIds.add(cdLink.ContentDocumentId);  
     }      
     DocumentList = [select Id,Title,FileType,ContentSize,Description from ContentDocument where id IN: documentIds];  
     return DocumentList;  // Return list of files on parent record
   }  
 }  



Output:
Steps to create quick Action:

  • Go to object manager and click on the Object for that you want to create 'New Action'.
  • Click on 'Buttons Links and Action' and then click on 'New Action' button.
  • Select the 'Action Type' Lightning Component.
  • Select Lightning Component that you just created.
  • Enter Label and Name and click on Save button.
  • Go to object page layout and add this action there.



























































Hope this post helps many.

Thanks
Arun Kumar.

Share:
Location: Noida, Uttar Pradesh, India

8 comments:

  1. Amazing Really helpful.
    thanks Arun

    ReplyDelete
  2. Is there any way to upload documents in Document object using Lightning

    ReplyDelete
  3. I got similar requirement, instead of files and I want in Documents standard object. example PDF file has to store in specific document folder in document object. Please provide me any code snippet.

    ReplyDelete
  4. I got also same requirement,but little modification i done as per my business case..Big thanks for your code reference..

    ReplyDelete
    Replies
    1. Great! Glad that you found this helpful. Hope this will help others too.

      Delete
  5. Thanks a lot for sharing Arun ! Helped me a lot

    ReplyDelete
  6. Helpful Content!

    is there anything through which we can open camera and not album/gallery in mobile app? basically i want to restrict user to upload camera captured photos only or atleast an event through which we can get the created date of the file being uploaded?

    ReplyDelete
  7. Great post!! This can be one particular of the most useful blogs We’ve ever arrive across on this subject. Basically Wonderful. I am also a specialist in this topic so I can understand your hard work.
    Document Management Software Dubai
    Document Management Software
    Document Management Software UAE
    Best Document Management Software

    ReplyDelete

Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *