To create a file upload component in Lightning Web Components (LWC) for Salesforce, you can utilize the built-in lightning-file-upload component and handle the file upload logic in the corresponding JavaScript file. Here's an example of how you can implement a file upload component in LWC:
uploadFile:
<template>
<lightning-card title="File Upload Component">
<lightning-file-upload
label="Upload File"
name="fileUploader"
accept=".pdf,.png,.jpeg"
record-id={recordId}
onuploadfinished={handleUploadFinished}>
</lightning-file-upload>
</lightning-card>
</template>
uploadFile.js:
import { LightningElement, api } from 'lwc';
export default class UploadFile extends LightningElement {
@api recordId;
handleUploadFinished(event) {
const uploadedFiles = event.detail.files;
// Perform any necessary logic with the uploaded files
// For example, you can retrieve the file IDs and perform additional actions
for (let i = 0; i < uploadedFiles.length; i++) {
console.log('File Uploaded: ' + uploadedFiles[i].name);
console.log('File ID: ' + uploadedFiles[i].documentId);
}
}
}
In this example, the lightning-file-upload component is used to display a file upload input field with the label "Upload File." The accept attribute specifies the file types allowed for upload (in this case, .pdf, .png, and .jpeg). The record-id attribute is used to associate the uploaded file with a specific record in Salesforce.
When a file is uploaded, the onuploadfinished event is triggered, and the handleUploadFinished method is called. In this method, you can perform any necessary logic with the uploaded files. For demonstration purposes, the code logs the file name and file ID to the console. You can customize this logic based on your specific requirements, such as saving the file details to a Salesforce record or performing additional processing.
To use this component in a parent component or record page, include it using the appropriate syntax:
<c-upload-file record-id={recordId}></c-upload-file>
Ensure that the necessary recordId attribute is passed to the component, either from a parent component or from the record page context.
Remember to include the required import statements and component registration in the appropriate places.
That's it! With this code, you have implemented a file upload component in LWC for Salesforce, allowing users to upload files and perform custom logic upon upload completion.