How To Create New Record along with File Upload in Lightning Web Component(LWC) :
In this post we are going to see how to upload files/attachments into Salesforce object by using Lightning Web Component. If we use "lightning-file-upload" tag we cant insert file along with record (yet to be inserted into database). Because lightning-file-upload requires record id for enabling upload option, but at that time record id not available as record not inserted yet. So we are using lightning-input type="file" tag for uploading file. But if we use this we need to write our own logic to insert file using apex unlike "lightning-file-upload". By using this we can upload JPEG, PNG images, Pdf etc. Check below example code.
In this post we are going to see how to upload files/attachments into Salesforce object by using Lightning Web Component. If we use "lightning-file-upload" tag we cant insert file along with record (yet to be inserted into database). Because lightning-file-upload requires record id for enabling upload option, but at that time record id not available as record not inserted yet. So we are using lightning-input type="file" tag for uploading file. But if we use this we need to write our own logic to insert file using apex unlike "lightning-file-upload". By using this we can upload JPEG, PNG images, Pdf etc. Check below example code.
Example: Create New Contact Record form along with File upload option:
Step 1: Create a apex controller for handling contact record and file insertion.
ContactController
public with sharing class ContactController {
@AuraEnabled
public static string saveContact(Contact contactRec, string file, string fileName) {
string contactId;
try{
Insert contactRec;
contactId = contactRec.Id;
String base64File = EncodingUtil.urlDecode(file, 'UTF-8');
ContentVersion contentVersionRec = new ContentVersion();
contentVersionRec.Title = fileName;
contentVersionRec.PathOnClient = '/' + fileName;
contentVersionRec.FirstPublishLocationId = contactRec.Id;
contentVersionRec.VersionData = EncodingUtil.base64Decode(base64File);
contentVersionRec.IsMajorVersion = true;
Insert contentVersionRec;
} catch(Exception ex){
system.debug('Exception===>'+ex.getMessage());
}
return contactId;
}
}
Step 2: Create Lightning Web Component
newRecordWithFileUpload.js
import { LightningElement, track } from 'lwc';
import saveRecord from '@salesforce/apex/ContactController.saveContact';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const MAX_FILE_SIZE = 100000000; //10mb
export default class NewRecordWithFileUpload extends NavigationMixin(LightningElement) {
@track name;
@track phone;
@track email;
@track description;
uploadedFiles = []; file; fileContents; fileReader; content; fileName
onNameChange(event) {
this.name = event.detail.value;
}
onPhoneChange(event) {
this.phone = event.detail.value;
}
onEmailChange(event) {
this.email = event.detail.value;
}
onDescriptionChange(event) {
this.description = event.detail.value;
}
onFileUpload(event) {
if (event.target.files.length > 0) {
this.uploadedFiles = event.target.files;
this.fileName = event.target.files[0].name;
this.file = this.uploadedFiles[0];
if (this.file.size > this.MAX_FILE_SIZE) {
alert("File Size Can not exceed" + MAX_FILE_SIZE);
}
}
}
saveContact() {
this.fileReader = new FileReader();
this.fileReader.onloadend = (() => {
this.fileContents = this.fileReader.result;
let base64 = 'base64,';
this.content = this.fileContents.indexOf(base64) + base64.length;
this.fileContents = this.fileContents.substring(this.content);
this.saveRecord();
});
this.fileReader.readAsDataURL(this.file);
}
saveRecord() {
var con = {
'sobjectType': 'Contact',
'LastName': this.name,
'Email': this.email,
'Phone': this.phone,
'Description': this.description
}
saveRecord({
contactRec: con,
file: encodeURIComponent(this.fileContents),
fileName: this.fileName
})
.then(conId => {
if (conId) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
variant: 'success',
message: 'Contact Successfully created',
}),
);
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: conId,
objectApiName: 'Contact',
actionName: 'view'
},
});
}
}).catch(error => {
console.log('error ', error);
});
}
}
newRecordWithFileUpload.html
<template>
<div class="slds-box slds-theme_default">
<div class="slds-m-around_medium">
<lightning-input type="text" label="Name" onchange={onNameChange}></lightning-input>
<lightning-input type="tel" label="Phone" onchange={onPhoneChange}></lightning-input>
<lightning-input type="email" label="Email" onchange={onEmailChange}></lightning-input>
<lightning-textarea name="input3" label="Description" onchange={onDescriptionChange}
placeholder="type here..."></lightning-textarea>
<lightning-input type="file" onchange={onFileUpload} required name="uploadFile" label="Upload File">
</lightning-input>
</div>
<div class="slds-align_absolute-center">
<lightning-button label="Save" onclick={saveContact}>
</lightning-button>
</div>
</div>
</template>
Step 3 : Add this File Upload Lightning Web Component to Lightning App Page
Add this newRecordWithFileUpload LWC component to any lightning page.
Output:
Ps: on above example we did not add validations, make sure that add your own validations.
Ps: on above example we did not add validations, make sure that add your own validations.
how to achieve this through aura component?
ReplyDelete