Upload Custom File in Lightning Web Component(LWC)

by Rijwan Mohmmed
10 comments
upload-custom-file-in-lightning-web-component(lwc)-techdicer

Hello friends, today we will discuss How to Upload Custom File in Lightning Web Component(LWC). We will upload files on a specific sObject record in Apex Class by Content Version. We will pass the base64 file and its info to Apex class by Lightning Web Component(LWC).

Also check this: How to Parse JSON Response in Apex Salesforce

Highlights Points :

  1. Can get File info.
  2. Avoid specific file type for upload.
  3. We Can change file name before file upload.
  4. Put Max Limit size for file upload.
  5. Show success and error toast on Apex response.

Process :

First, we create an LWC component so we can easily upload the files and on Apex Class we can insert this file on a particular sObject Records.

Code :

Step1: Here we create an Apex Class for upload the files in the Salesforce Org.

CustomFileUploadLWCCtrl.cls:

public class CustomFileUploadLWCCtrl {

    @AuraEnabled
    public static String uploadFile(String fileName, String base64Data, Id recordId) {
        // Decoding the base64Data
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        ContentVersion cv = new ContentVersion();
        cv.Title = fileName;
        cv.PathOnClient = '/' + fileName;
        cv.FirstPublishLocationId = recordId;
        cv.VersionData = EncodingUtil.base64Decode(base64Data);
        cv.IsMajorVersion = true;
        Insert cv;
        return 'File upload successfully!';
    }
}

Step2: In this step, we create Lightning Web Component(LWC) for the UI part. On this HTML part, we put the input field which type is file also put accept files types. In the Js part, we will read the file and make a base64.

CustomFileUploadLWC.HTML :

<template>
	  <!-- loader -->
    <div if:true={showSpinner}>
        <lightning-spinner
            alternative-text="Loading..." variant="brand" class="slds-is-fixed">
        </lightning-spinner>
    </div>
    <!-----/loader------>
    <!----header -->
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>Box API Call From Apex</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <!----/header -->
    <!-- Upload files card -->
    <lightning-card  variant="Narrow"  title="Upload Files" icon-name="standard:file">
        <div class="slds-var-p-around_small">
            <lightning-layout multiple-rows>
				<lightning-layout-item padding="around-small" size="12" medium-device-size="12" large-device-size="12">
                    <lightning-input label="File" name="file uploader" 
                                     onchange={handleFileChange} type="file"
                                     accept=".jpg, .csv, .png, .doc, .pdf">
                    </lightning-input>
					<p if:true={fileName}>{fileName}</p>
				</lightning-layout-item>

                <lightning-layout-item size="12" class="slds-var-p-top_small">
					<lightning-button class="slds-align_absolute-center" variant="brand" label="Upload Files"
						onclick={uploadFile}>
                    </lightning-button>
				</lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card>
    <!-- /Upload files card -->
</template>

CustomFileUploadLWC.JS :

import { LightningElement, track, api } from 'lwc';
import uploadFile from '@salesforce/apex/CustomFileUploadLWCCtrl.uploadFile';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class CustomFileUploadLWC extends LightningElement {
    @track showSpinner = false;
    @track fileData;
    @api recordId;
    @track fileName;
     // getting file 
    handleFileChange(event) {
        if(event.target.files.length > 0) {
            const file = event.target.files[0]
            var reader = new FileReader()
            reader.onload = () => {
                var base64 = reader.result.split(',')[1]
                this.fileName = file.name;
                this.fileData = {
                    'filename': file.name,
                    'base64': base64
                }
                console.log(this.fileData)
            }
            reader.readAsDataURL(file)
        }
    }

    uploadFile() {
        this.handleSpinner();
        const {base64, filename} = this.fileData

        uploadFile({ fileName:this.fileName, base64Data : base64, recordId:this.recordId }).then(result=>{
            this.fileData = null
            let title = `${filename} uploaded successfully!!`;
            this.ShowToast('Success!', title, 'success', 'dismissable');
            this.updateRecordView(this.recordId);
        }).catch(err=>{
            this.ShowToast('Error!!', err.body.message, 'error', 'dismissable');
        }).finally(() => {
            this.handleSpinner();
        })
    }

    handleSpinner(){
        this.showSpinner = !this.showSpinner;
    }

    ShowToast(title, message, variant, mode){
        const evt = new ShowToastEvent({
            title: title,
            message:message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(evt);
    } 

    //update the record page
    updateRecordView() {
       setTimeout(() => {
            eval("$A.get('e.force:refreshView').fire();");
       }, 1000); 
    }
}

Output :

upload-custom-file-in-lightning-web-component(lwc)-output-techdicer
upload-custom-file-in-lightning-web-component(lwc)-output-techdicer

Reference :

  1. Salesforce

You may also like

10 comments

Smita Ambolikar June 27, 2022 - 2:27 pm

Hey, Its good but doesn’t show us the file upload progress bar & I want to upload file with size more than 10 mb, how to achieve that?

Reply
Rijwan Mohmmed June 27, 2022 - 3:36 pm

Hi @Smita Ambolikar, I will create a new blog to show the progress bar on File upload. Can you please share the error message when you upload more then 10 MB File.
meanwhile you can check this link => https://salesforce.stackexchange.com/questions/304768/how-to-call-lwc-function-in-xmlhttprequest-xhr-post-request-methods
https://salesforce.stackexchange.com/questions/281357/how-to-upload-larger-size-file-using-input-tag-of-type-html-in-lwc/330411#330411

Reply
shweta Bondre August 22, 2022 - 5:34 am

Content is really very helpful but can we upload folders same as files

Reply
Rijwan Mohmmed August 22, 2022 - 7:41 am

Hi @Shweta, you can create a ZIP file of folder and then upload

Reply
Dan August 1, 2022 - 8:09 am

hey i want to create lwc which uploads files to sharepoint ,how to do it?

Reply
Rijwan Mohmmed August 1, 2022 - 6:06 pm

you can do this by direct upload files to share point from LWC or from Apex

Reply
shweta Bondre August 22, 2022 - 5:36 am

I want to create LWC to upload folders and files to azure, any suggestion to do this

Reply
Rijwan Mohmmed August 25, 2022 - 3:44 pm Reply
Erick August 26, 2022 - 6:26 pm

I want to create a LWC to upload files that allow to upload multiple files and remove the files before submitting them. Any idea of how to implement this? It looks like the lightning-file-upload does not allow that.

Reply
Rijwan Mohmmed August 29, 2022 - 7:23 am

Hi @Erick, are you want to delete the files then you write trigger on Content Version
Can you please explain something more?

Reply

Leave a Comment