Salesforce doesn’t give direct uploading of files into your SF library using lightning-input. Also, you can’t see or remove the files which are uploaded, you need to refresh back your page. With the help of this code, you can upload and remove the uploaded files easily. You can see uploaded files names as well. For each file you upload, its name will be visible with a cross icon to remove the file.
Component Features:
- Upload multiple files at once
- Uploaded file names will be visible below file upload.
- Ability to remove uploaded files.
Component Preview:
Step-1: Create an Apex controller
We need to create an Apex class first which will take our file data and create Content Version and Content Link records. Note that the Content Document record will be created automatically when you create a Content Version record.
Now create FileUploadMultiController.cls Apex class and paste the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
/* Code by CafeForce || www.cafeforce.com || support@cafeforce.com || Mandatory Header */ public class FileUploadMultiController { @AuraEnabled public static String uploadFiles(String recordId, String filedata) { try { if(String.isNotBlank(FileData)) { List<FileDataWP> files = (List<FileDataWP>) JSON.deserialize(filedata, List<FileDataWP>.class); System.debug(files); List<ContentVersion> cvList = new List<ContentVersion>(); for(FileDataWP file : files) { ContentVersion conVer = new ContentVersion(); conVer.ContentLocation = 'S'; // S = Salesforce, E = External Files conVer.VersionData = EncodingUtil.base64Decode(file.fileContent); conVer.Title = file.fileName; conVer.PathOnClient = file.fileName; cvList.add(conVer); } Insert cvList; List<ContentDocumentLink> cdList = new List<ContentDocumentLink>(); for(ContentVersion cv : [SELECT ContentDocumentId FROM ContentVersion WHERE Id =: cvList]) { ContentDocumentLink conDocLink = New ContentDocumentLink(); conDocLink.LinkedEntityId = recordId; conDocLink.ContentDocumentId = cv.ContentDocumentId; conDocLink.Visibility = 'AllUsers'; conDocLink.shareType = 'V'; // V = Viewer, C = Collaborator, I = Inferred cdList.add(conDocLink); } Insert cdList; } else { return 'record Id is Blank'; } return 'success'; } catch (Exception ex) { System.debug(ex.getMessage() + ' -> ' + ex.getStackTraceString()); throw new AuraHandledException(ex.getMessage()); } } public class FileDataWP { public String fileName; public String fileContent; } } /* Code by CafeForce Website: http://www.cafeforce.com DO NOT REMOVE THIS HEADER/FOOTER FOR FREE CODE USAGE */ |
Step-2: Now we will create the fileUploadMultiLWC Lightning Web Component.
For creating a new Lightning Web Component, use any IDE like VS Code.
Markup for fileUploadMultiLWC.cmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!-- Code by CafeForce || www.cafeforce.com || support@cafeforce.com || Mandatory Header --> <template> <div class="slds-box slds-p-top_small" style="background-color: white; position: relative;"> <template if:true={showSpinner} > <lightning-spinner alternative-text="Loading" size="medium" class="spinnerClass"></lightning-spinner> </template> <div class="slds-text-heading_medium">Multiple Files Upload</div> <br/> <lightning-input type="file" label="Attachment" onchange={handleFileUploaded} multiple> </lightning-input> <template if:true={filesData}> <template for:each={filesData} for:item="imgName" for:index="index"> {imgName.fileName} <span key={imgName.fileName} data-id={index} onclick={removeReceiptImage} class="removeImage">x</span> </template> </template> <br/> <lightning-button variant="brand" label="Upload Files" onclick={uploadFiles} class="slds-m-top_medium"> </lightning-button> </div> </template> <!-- Code by CafeForce Website: http://www.cafeforce.com DO NOT REMOVE THIS HEADER/FOOTER FOR FREE CODE USAGE --> |
Now open the javascript file fileUploadMultiLWC.js and paste the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import {LightningElement,api,track} from 'lwc'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import uploadFiles from '@salesforce/apex/FileUploadMultiController.uploadFiles' const MAX_FILE_SIZE = 2097152; export default class FileUploadMultiLWC extends LightningElement { @api recordId; @track filesData = []; showSpinner = false; handleFileUploaded(event) { if (event.target.files.length > 0) { for(var i=0; i< event.target.files.length; i++){ if (event.target.files[i].size > MAX_FILE_SIZE) { this.showToast('Error!', 'error', 'File size exceeded the upload size limit.'); return; } let file = event.target.files[i]; let reader = new FileReader(); reader.onload = e => { var fileContents = reader.result.split(',')[1] this.filesData.push({'fileName':file.name, 'fileContent':fileContents}); }; reader.readAsDataURL(file); } } } uploadFiles() { if(this.filesData == [] || this.filesData.length == 0) { this.showToast('Error', 'error', 'Please select files first'); return; } this.showSpinner = true; uploadFiles({ recordId : this.recordId, filedata : JSON.stringify(this.filesData) }) .then(result => { console.log(result); if(result && result == 'success') { this.filesData = []; this.showToast('Success', 'success', 'Files Uploaded successfully.'); } else { this.showToast('Error', 'error', result); } }).catch(error => { if(error && error.body && error.body.message) { this.showToast('Error', 'error', error.body.message); } }).finally(() => this.showSpinner = false ); } removeReceiptImage(event) { var index = event.currentTarget.dataset.id; this.filesData.splice(index, 1); } showToast(title, variant, message) { this.dispatchEvent( new ShowToastEvent({ title: title, variant: variant, message: message, }) ); } } /* Code by CafeForce Website: http://www.cafeforce.com DO NOT REMOVE THIS HEADER/FOOTER FOR FREE CODE USAGE */ |
Now finally paste the CSS in the fileUploadMultiLWC.css file.
If CSS file doesn’t exist. Right-click on the LWC component folder and click on create new File. Name it fileUploadLWC.css
1 2 3 4 5 6 7 8 9 10 |
.removeImage { border-radius: 50%; padding: 0px 4px; margin: 8px 2px 8px 8px; color: #fff; background-color: #9f201b; cursor: pointer; } |
Now, if you want to add this component to your Record Detail Page, add the below code to your component meta file.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>51.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle> |
Step-3: Now we will call the component.
To see the output, go to your Record Detail page, click on the setting gear icon on top and click on Edit Page. Lightning App Builder will open, find your component in the left sidebar and drop it onto the screen. Activate and Save the page and click on the back button. Your component will be visible now the screen now.
Also Check:
For any queries or suggestions, comment below.
Cheers … Happy Coding … 🙂
how do i get @api recordId
Hi, You just need to import api on top.