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