Showing posts with label file upload in lightning web components. Show all posts
Showing posts with label file upload in lightning web components. Show all posts

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