Many time we get requirement to uploading multiple files using lightning component. This post give detail about how to upload multiple files.
Steps to complete this requirement
- Create Apex class which will save record in record as attachement
- Create Lightning Component to upload documents
- Add above created component in page to test it
1. Create Apex class to save record
we need to create apex class to save selected files in record as attachment. Files which is uploaded first time will be created as attachment. Already uploaded files will be update with new contents.
Apex Code:
2. Create Lightning Component
Create Lightning component which will upload files in current record. Current record means it will take record id of record where this component will be uploaded. If component is added on case record, then it will take current case record id. If component is added on account record, then it will take current account record id and same for other object as well. We have to implement interface force:hasRecordId to use current record id.
implements="force:hasRecordId"
We have to declare recordId attribute like this.
<aura:attribute name="recordId" type="Id" />
We can add toast to show message or error while uploading files.
showMessage : function(message,isSuccess) { var toastEvent = $A.get("e.force:showToast"); toastEvent.setParams({ "title": isSuccess?"Success!":"Error!", "type":isSuccess?"success":"error", "message": message }); toastEvent.fire(); }
We can use lightning:input for uploading multiple files
<lightning:input aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="file" label="" multiple="true"/>
We can get numbers of files uploaded using below script in controller/helper class. Based on files count we can upload files in loop.
var fileCount=component.find("fileId").get("v.files").length;
Complete Lightning Component Code
3. Testing Created Lightning Component
References: https://developer.salesforce.com/docs/component-library/bundle/lightning:input