0

I have lightning-input tag with type as file in Child component, and I am making use of this child component in Parent component which contains Submit button. So when the user clicks on submit , file should be uploaded.

fileUploadChild.html

<template>
    <div class="slds-m-around_medium">
        <lightning-input type="file" 
        accept=".xlsx, .xls, .csv, .png, .doc, .docx, .pdf"
        label="Upload Files" onchange={openfileUpload} ></lightning-input>
    </div>
</template>

fileUploadChild.js

import { LightningElement,track,api } from 'lwc';

export default class FileUploadChild extends LightningElement {
    @api recordId;
    @track fileNames;
    @track fileData;

    openfileUpload(event) {
        const file = event.target.files[0]
        var reader = new FileReader()
        reader.onload = () => {
            var base64 = reader.result.split(',')[1]
            this.fileData = {
                'base64': base64,
                'filename': file.name,
            }
            console.log('file data'+this.fileData)

            const customEvent = new CustomEvent("filedatachild",{
                detail: JSON.stringify(this.fileData)
            });
    
            this.dispatchEvent(customEvent)
        }
        reader.readAsDataURL(file)
        console.log('file'+file.name);

    }  
}

I am sending the file info through events.

Now how do I handle the event in Parent and submit the file?

1 Answer 1

1

Figured it out!!

Have handled the file data in parent and on submit passed file data to apex method which in turn creates a file.

FileUpload.html

<template>
    <lightning-card title="File Upload Demo LWC" icon-name="custom:custom14">
        <c-file-upload-child onfiledatachild={handleChildFileData}></c-file-upload-child>
        <template if:true={fileData}>
            <p>{fileData.filename}</p>
        </template>
        <lightning-button variant="brand" label="submit" title="Submit" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    </lightning-card>
</template>

fileUpload.js

import { LightningElement, api,track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import uploadFile from '@salesforce/apex/FileUploaderClass.uploadFile'
export default class FileUploaderCompLwc extends LightningElement {
    @api recordId;
    @track fileNames;
    @track fileData;

        handleChildFileData(event){
        console.log('Parent record Id'+this.recordId);
        this.fileData = JSON.parse(event.detail);
        console.log('Parent File Data'+JSON.stringify(this.fileData));
    }
    
    handleClick(){
        const {base64, filename} = this.fileData
        const recordId = this.recordId
        console.log('recId'+recordId);
        uploadFile({ base64, filename, recordId }).then(result=>{
            this.fileData = null
            let title = `${filename} uploaded successfully!!`
            this.toast(title)
        })
    }

    toast(title){
        const toastEvent = new ShowToastEvent({
            title, 
            variant:"success"
        })
        this.dispatchEvent(toastEvent)
    }
}

FileUploaderClass

public with sharing class FileUploaderClass {
    
@AuraEnabled
  public static String uploadFile(String base64, String filename, String recordId) {
        ContentVersion cv = createContentVersion(base64, filename);
        ContentDocumentLink cdl = createContentLink(cv.Id, recordId);
        if (cv == null || cdl == null) { return null; }
        return cdl.Id;
  }

  private static ContentVersion createContentVersion(String base64, String filename) {

    //String modifiedFileName = fileName+ '0000';
    ContentVersion cv = new ContentVersion();
    cv.VersionData = EncodingUtil.base64Decode(base64);
    cv.Title = fileName;
    cv.PathOnClient = fileName;
    try {
      insert cv;
      return cv;
    } catch(DMLException e) {
      System.debug(e);
      return null;
    }
  }

  private static ContentDocumentLink createContentLink(String contentVersionId, String recordId) {
              if (contentVersionId == null || recordId == null) { return null; }
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = [
      SELECT ContentDocumentId 
      FROM ContentVersion 
      WHERE Id =: contentVersionId
    ].ContentDocumentId;
    cdl.LinkedEntityId = recordId;
    // ShareType is either 'V', 'C', or 'I'
    // V = Viewer, C = Collaborator, I = Inferred
    cdl.ShareType = 'V';
    try {
      insert cdl;
      return cdl;
    } catch(DMLException e) {
      System.debug(e);
      return null;
    }
  }
}
1
  • Thanks for coming back and adding the solution you worked out. It's good to know a question was answered, and could be helpful to future readers/seekers. It is also completely fine (encouraged, actually, if it is the only or best answer) to accept your own answer.
    – Moonpie
    Aug 3, 2022 at 12:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .