Wednesday, March 13, 2019

File upload component in lightning web components(lwc)

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.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

4 comments:

  1. I can't upload, because upload button disable.
    how to enable the button?

    ReplyDelete
    Replies
    1. pass record-id={recordId} like this, 'recordId' is Case Sensitive pass same like this.

      Delete
  2. Super its working fine

    ReplyDelete
  3. can we restrict file upload size?like more than 2mb show an error?

    ReplyDelete