How to upload files in Lightning Web Component (LWC) Salesforce

by Rijwan Mohmmed

We will use lightning-file-upload for file upload. We can upload multiple files with this. With Lightning Web Components, you can empower users to upload files directly within your app, enhancing user engagement and productivity.

🌟 Why It’s Awesome:

  1. Effortless User Experience: Simplify file uploads for users with an intuitive interface that aligns with their expectations.
  2. Streamlined Data: Attach files directly to records, keeping your data organized and accessible in one place.
  3. Boosted Productivity: Enable users to focus on tasks instead of file management logistics.

🔧 Process & Coding :

lightning-file-upload base component with the below attributes :

  • label: Label for the Upload Files button.
  • name: Name of the component.
  • accept: To restrict the File Types. Only Files Types provided in the list are supported for uploading.
  • record-id: To associate uploaded files to a particular record.
  • onuploadfinished: This method will be called once the file is uploaded successfully.
  • multiple : To upload multiple files
<lightning-file-upload
            label="File Upload"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={myRecordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>

fileupload.html :

<template>
    <lightning-card title="File Upload in LWC">
        <div class="slds-p-horizontal_x-small" >
            <lightning-layout>
                <lightning-layout-item size="12">
                    <div class="slds-p-left_medium">
                        <lightning-file-upload
                            label="Attach Files"
                            name="uploadFile"
                            accept={acceptedFormats}
                            record-id={recordId}    
                            onuploadfinished={handleUploadFinished} multiple>
                        </lightning-file-upload>
                    </div> 
                </lightning-layout-item>
            </lightning-layout>
            <br/>
            <lightning-layout>    
                <lightning-layout-item size="12">
                    <div class="slds-p-left_medium">
                       <h2> Uploaded Files:</h2> <br/>
                        <table class="slds-table slds-table_cell-buffer slds-table_bordered" aria-label="Example default base table of Opportunities">
                            <thead>
                                <tr class="slds-line-height_reset">
                                    <th class="" scope="col">
                                        <div class="slds-truncate" title="File Name">File Name</div>
                                    </th>
                                    <th class="" scope="col">
                                        <div class="slds-truncate" title="File Size">File Type</div>
                                    </th>
                                    <th class="" scope="col">
                                        <div class="slds-truncate" title="File Size">File Size</div>
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <template for:each={lstAllFiles} for:item="fileIterator">
                                    <tr class="slds-hint-parent" key={fileIterator}>
                                        <th data-label="Opportunity Name" scope="row">
                                            <lightning-icon icon-name="doctype:image" size="small" title="Image"></lightning-icon>
                                            {fileIterator.ContentDocument.Title}
                                        </th>
                                        <td data-label="Account Name">
                                            <div class="slds-truncate" title="Cloudhub">
                                                {fileIterator.ContentDocument.FileType}
                                            </div>
                                        </td>
                                        <td data-label="Account Name">
                                            <div class="slds-truncate" title="Cloudhub">
                                                {fileIterator.ContentDocument.ContentSize} Byte
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card>
</template>

fileupload.js :

import { LightningElement, track,api } from 'lwc';
import fetchFiles from '@salesforce/apex/Fileuploadcttrl.fetchFiles';
export default class Fileupload extends LightningElement {
    @api recordId;
    @track lstAllFiles;
    @track error;
    get acceptedFormats() {
        return ['.pdf','.png','.jpg'];
    }

    handleUploadFinished(event) {
        this.connectedCallback();
    }

    connectedCallback() {
        fetchFiles({recordId:this.recordId})
        .then(result=>{
            this.lstAllFiles = result; 
            this.error = undefined;
        }).catch(error=>{
            this.lstAllFiles = undefined; 
            this.error = error;
        })
    }
}

fileupload.js-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>51.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__RecordPage</target>
	</targets>
</LightningComponentBundle>

Fileuploadcttrl.cls :

public class Fileuploadcttrl {
    @AuraEnabled(cacheable=false)
    public static List<ContentDocumentLink> fetchFiles(String recordId){
        return [SELECT LinkedEntityId, ContentDocument.CreatedDate, ContentDocument.Title, ContentDocument.ContentSize, ContentDocument.FileType 
                    FROM ContentDocumentLink  
                WHERE LinkedEntityId  =:recordId];
    }
}

Output :

What’s your Reaction?
+1
6
+1
4
+1
1
+1
1
+1
4
+1
4

You may also like

9 comments

How to create Reusable custom lookup in Lightning Web Component (LWC) Salesforce - Techdicer September 12, 2021 - 3:19 pm

[…] Link Upload files in LWC Salesforce […]

Reply
John May 18, 2022 - 8:27 pm

That is when you have the recordId, What about when is a form ? When Creating a support case you need attachments. who do you add the files?

Reply
Rijwan Mohmmed May 23, 2022 - 3:38 pm

In your case, you can use a custom file upload LWC component.
Upload Custom File in Lightning Web Component(LWC)

Reply
Asad June 23, 2022 - 12:13 pm

How about when I want to send Uploaded file to my Component, how to I catch that?

Reply
Rijwan Mohmmed June 25, 2022 - 6:43 am

Hi @Asad Can you please explain more about this

Reply
anonymous August 5, 2022 - 8:40 am

Hi, I want to upload multiple files of large size to box folder from salesforce. Could you Please tell me how can I do that?

Reply
Rijwan Mohmmed August 6, 2022 - 5:55 pm

By Salesforce Apex, I don’t think so we can but you can do it by LWC HTTP call out, below is my blog
https://techdicer.com/upload-image-by-http-callout-in-lwc/

Reply
Nagaraj October 10, 2022 - 4:22 am

Hi Bro ,
i am working Health cloud, my Lwc component i want standard Add file function instead of Upload file is there any possible?

Reply
Khumed March 26, 2023 - 4:25 pm

Hi RIJWAN MOHMMED I tried Your code Thanks for Posting I have posted the code on my blog with a detailed explanation and also added and Endorsed your Blog too

Reply

Leave a Comment