This post explains how to use file upload in lighting web component(lwc)
lightning-file-upload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.
Demo
fileUploadLWCdemo.js
fileUploadLWCdemo.js-meta.xml
Result
lightning-file-upload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.
Demo
fileUploadLWCdemo.html
<template>
    <lightning-card title='File Uploadr' icon-name="custom:custom19">
        <lightning-file-upload
                label="Attach receipt"
                name="fileUploader"
                accept={acceptedFormats}
                record-id={recordId}
                onuploadfinished={handleUploadFinished}
                multiple>
            </lightning-file-upload>
    </lightning-card>
</template>
fileUploadLWCdemo.js
import { LightningElement, api } from 'lwc';
// imported to show toast messages
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class FileUploadLWCdemo extends LightningElement {
    @api
    recordId;
    // accepted parameters
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        let strFileNames = '';
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        for(let i = 0; i < uploadedFiles.length; i++) {
            strFileNames += uploadedFiles[i].name + ', ';
        }
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success!!',
                message: strFileNames + ' Files uploaded Successfully!!!',
                variant: 'success',
            }),
        );
    }
}
fileUploadLWCdemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="fileUploadLWCdemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Result

I can't upload, because upload button disable.
ReplyDeletehow to enable the button?
pass record-id={recordId} like this, 'recordId' is Case Sensitive pass same like this.
DeleteSuper its working fine
ReplyDeletecan we restrict file upload size?like more than 2mb show an error?
ReplyDeleteIs there a way to make the file drop area bigger?
ReplyDelete