How to Upload a File Using Lightning Web Component in Salesforce?

In Salesforce, using a Lightning Web Component, we can create a custom component for uploading files. With this, we can upload files, such as documents, images, or PDFs, and store them as Files or documents.

In this Salesforce tutorial, we will learn how to upload a file using the lightning web component in Salesforce.

Upload a File Using Lightning Web Components in Salesforce

In the example below, we will create a Lightning web component using the lightning-upload component to handle file selection and upload.

1. First, we will create an Apex controller class to process the file or attach it programmatically. This will handle the uploads by processing base64-encoded file data, storing it as a Salesforce file, and linking it to a record.

Base64 encoded binary documents, access the document directly using the Id, rather than decoding Base64 in JavaScript.

public with sharing class FileUploaderClass {
      @AuraEnabled
  public static String uploadFile(String base64, String filename, String recordId) {
        ContentVersion cv = createContentVersion(base64, filename);
        ContentDocumentLink cdl = createContentLink(cv.Id, recordId);
        if (cv == null || cdl == null) { return null; }
        return cdl.Id;
  }
    private static ContentVersion createContentVersion(String base64, String filename) {
    ContentVersion cv = new ContentVersion();
    cv.VersionData = EncodingUtil.base64Decode(base64);
    cv.Title = filename;
    cv.PathOnClient = filename;
    try {
      insert cv;
      return cv;
    } catch(DMLException e) {
      System.debug(e);
      return null;
    }
  }
 private static ContentDocumentLink createContentLink(String contentVersionId, String recordId) {
              if (contentVersionId == null || recordId == null) { return null; }
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = [
      SELECT ContentDocumentId 
      FROM ContentVersion 
      WHERE Id =: contentVersionId
    ].ContentDocumentId;
    cdl.LinkedEntityId = recordId;
      cdl.ShareType = 'V';
    try {
      insert cdl;
      return cdl;
    } catch(DMLException e) {
      System.debug(e);
      return null;
    }
  }
}

In the above class, we have used the method uploadFile that accepts a Base64-encoded file, its filename, and a target record ID.

This method creates a ContentVersion record to store the file and then creates a link between the file and the specified record using a ContentDocumentLink. It ensures that the uploaded file is stored correctly and associated with the Salesforce record.

2. Create an LWC component “fileUploader” and enter the below code in the HTML file.

<template>
    <lightning-card title="File Upload Demo LWC" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input type="file" 
            accept=".xlsx, .xls, .csv, .png, .doc, .docx, .pdf"
            label="Attachment" onchange={openfileUpload}></lightning-input>
        </div>
        <template if:true={fileData}>
            <p>{fileData.filename}</p>
        </template>
        <lightning-button variant="brand" label="submit" title="Submit" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    </lightning-card>
</template>

In the above code, <lightning-input type=”file”> tag allows users to select a file. This input field accepts files in .xlsx, .xls, .csv, .png, .doc, .docx, and .pdf formats.

The “Submit” button triggers the handleClick method to upload the file. When a file is selected, the openfileUpload method is triggered.

3. After this, enter the code below in the JS file to define the logic of uploading the file in the Files object and also display a success toast notification on a successful upload.

In this, we have imported the apex method uploadFile then defined fileData to store file details.

import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import uploadFile from '@salesforce/apex/FileUploaderClass.uploadFile'
export default class FileUploaderCompLwc extends LightningElement {
    @api recordId;
    fileData
    openfileUpload(event) {
        const file = event.target.files[0]
        var reader = new FileReader()
        reader.onload = () => {
            var base64 = reader.result.split(',')[1]
            this.fileData = {
                'filename': file.name,
                'base64': base64,
                'recordId': this.recordId
            }
            console.log(this.fileData)
        }
        reader.readAsDataURL(file)
    }
    
    handleClick(){
        const {base64, filename, recordId} = this.fileData
        uploadFile({ base64, filename, recordId }).then(result=>{
            this.fileData = null
            let title = '${filename} uploaded successfully!!'
            this.toast(title)
        })
    }

    toast(title){
        const toastEvent = new ShowToastEvent({
            title, 
            variant:"success"
        })
        this.dispatchEvent(toastEvent)
    }
}

In the above code, we have imported the uploadFile method from the Apex class FileUploaderClass to handle the file upload process

In this, we have declared two properties: recordId, representing the ID of the record to which the file will be attached, and fileData, an object storing the file’s name, Base64-encoded content, and the associated recordId.

The openfileUpload method is triggered when a user selects a file; it reads it using the FileReader API, converts its content to a Base64 string, and stores the result in fileData. On a successful upload, it displays a toast notification using lightning platformShowToastEvent.

4. Enter the below code in the meta.xml file to make the component visible to the lightning pages.

 <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

5. After this, deploy the LWC component to the Lightning page, and there you will see the UI of the file uploader. Here, either you can drag and drop the file or click on the Upload Files button to browse it.

Make sure that you have selected the file format that is supported in the input.

Upload Files Using LWC in Salesforce

When the file is uploaded correctly, its name will be visible above the submit button. At last, click Submit to upload the file.

Salesforce LWC File Uploader

On a successful upload, a success toast notification will appear on the screen.

Create an LWC component to Upload Files in Salesforce

This way, we can create a Lightning web component through which we can upload a file in the Salesforce.

Conclusion

In this Salesforce tutorial, we have learned how to upload files in Salesforce using a Lightning Web Component. In the above steps, we created an apex controller to handle file storage and an LWC component for file selection, then implemented the logic to convert and upload files in Base64 format.

By using the lightning-input component and calling the Apex method, we successfully stored files in Salesforce and linked them to specific records.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.