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 :
- Can get File info.
- Avoid specific file type for upload.
- We Can change file name before file upload.
- Put Max Limit size for file upload.
- 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);
}
}
20 comments
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?
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
Content is really very helpful but can we upload folders same as files
Hi @Shweta, you can create a ZIP file of folder and then upload
hey i want to create lwc which uploads files to sharepoint ,how to do it?
you can do this by direct upload files to share point from LWC or from Apex
I want to create LWC to upload folders and files to azure, any suggestion to do this
Hi @shweta,
Check this blog
https://techdicer.com/upload-image-by-http-callout-in-lwc/
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.
Hi @Erick, are you want to delete the files then you write trigger on Content Version
Can you please explain something more?
Hi @Rijawan
Really helpful
we need to upload the file and need to display in the related list(list of files) with out using Apex class and we can use lightning-file-upload functionality right.
Can we have any blog for this functionality and we saw your video in the YouTube but we can’t get the code.
YouTube Video Name: Upload files in lightning web component LWC salesforce.
https://techdicer.com/upload-files-in-lightning-web-component-lwc-salesforce/
Thanks for the post. However, is ther a way yo remove the Add Files button on the std component ( the component which is placed below your custom comp ? )
I think you can do by edit the page layout or on edit lightning page.
Nopes. I couln’t find any option. I think I will have to check at the permission set / profile level. The std File related list on the pagelayout is non-editable component. thank you.
I want to customize the Files component that is in the Cases related list. Is it possible to insert a checkbox button before the user clicks on upload files in this standard component?
Yes it Possible.
Can you share some ideia about this? I appreciate that
Hello, Thank you for the content. How do I trigger the Upload File in a modal upon clicking of a custom action on the layout?
You can create a modal popup and add my code there, it will work