0

I have a file upload LWC component that used to work but now it's throwing an "uploadn.map is not a function error" when I call reader.readAsDataURL(file). I imagine updates to locker service are to blame but wondering if anyone else has run into this or if there's a solution? At the end of the day I just want to upload an image

            <template if:true={showUpload}>
                <lightning-input type="file" 
                accept=".png, .gif, .jpg, .jpeg"
                label="" onchange={updateSignature} data-id="fileupload"></lightning-input>
            </template>
    updateSignature(event) {
        
        let file = event.target.files[0];
        console.log(event.target.files[0]);

        if(!file) {
            const toast = new ShowToastEvent({
                "title" : "Error",
                "message": "Please select a file",
                "variant": "error"
            });
            this.dispatchEvent(toast);
            return;
        }
        
        let reader = new FileReader();
        reader.onload = () => {
            let parts = reader.result.split(',');
            updateSignatureImage({recordId: this.recordId, base64Image: parts[1]}).then(result => {
                
                this.update = false;
                this.uploaded = true; 
                refreshApex(this.getRecord);
                getRecordNotifyChange(this.recordId);
                const toast = new ShowToastEvent({
                    "title" : "Success!",
                    "message": "Signature image updated successfully",
                    "variant": "success"
                });
                this.dispatchEvent(toast);

            }).catch(error => {

                const toast = new ShowToastEvent({
                    "title" : "Error",
                    "message": "Signature image failed to upload"+error.message,
                    "variant": "error"
                });
                this.dispatchEvent(toast);
            })
        }
        

        console.log('readingDataUrl');
        reader.readAsDataURL(file);
            
    } 

3
  • 2
    I agree lightning-file-upload should be used. Why don't you use it? Do you understand that even if you were able to make the existing solution work, it would be limited to 4MB files only since you can't process any bigger files in Apex due to heap size limit?
    – Patlatus
    Aug 30, 2023 at 9:17
  • Yes, only small size images needed to be uploaded so 4MB limit was not an issue and the solution did work in the past but started failing after a salesforce update. I think this solution was in use before salesforce had it's own file upload solution in LWC. If you search for file upload with LWC you'll still find tutorials using this solution. Sep 1, 2023 at 16:15
  • Just to confirm, lightning-file-upload didn't exist in API 39 Sep 1, 2023 at 16:34

1 Answer 1

2
+50

hope everything goes well.

I can see you're working on an image uploader in a Lightning Web Component and encountering an error. I'd recommend utilizing the standard Lightning Component lightning-file-upload (https://developer.salesforce.com/docs/component-library/bundle/lightning-file-upload/documentation) for your image upload needs, as it simplifies the process considerably, and as you're said it's just an IMGs uploader.

Here's an example of how you can achieve this:

In your template file

<template>
    <lightning-card title="Image Uploader">
        <h1>Record to relate: {recordId}</h1>
        <lightning-file-upload accept={acceptedIMGFormats} label="Upload Images" multiple="multiple"
            onuploadfinished={uploadFileHandler} record-id={recordId}></lightning-file-upload>
    </lightning-card>
</template>

JavaScript file

import { LightningElement, api, track } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import controllerPostOperations from '@salesforce/apex/DummyClass.controllerPostOperations';

export default class ImgUploader extends LightningElement {
    @track error;
    @track data;

    @api recordId;

    // accepted parameters
    get acceptedIMGFormats() {
        return ['.png', '.jpg', '.jpeg'];
    }
    
    uploadFileHandler(event) {
        // Get the list of records from the uploaded files
        const uploadedFiles = event.detail.files;

        // files are already uploaded
        // here I am passing the first documentId to the apex controller
        // to make any other post operations.
        // This is optional, you can remove this part if you don't need it.
        controllerPostOperations({contentDocumentId : uploadedFiles[0].documentId})
        .then(result => {
            window.console.log('result ===> '+result);
            this.data = result;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success!!',
                    message: 'post operation done!!!',
                    variant: 'Success',
                }),
            );
        })
        .catch(error => {
            this.error = error;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error!!',
                    message: JSON.stringify(error),
                    variant: 'error',
                }),
            );     
        })

    }
}

Apex Controller

public with sharing class DummyClass {
    @AuraEnabled
    public static String controllerPostOperations(String contentDocumentId) {
        try {
            // Perform your post-upload operations here
            return 'Done';
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

Hope this helps you,

1
  • 1
    Thank you, this component didn't exist when this component was originally written :) I suppose it makes sense for salesforce to push a breaking change to push developers to this component. Sep 1, 2023 at 16:40

You must log in to answer this question.

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