Convert event.target.files into a JSON string

I am trying to send uploaded file via a JSON. However I am unable to send the file attribute directly in below way.

<template>
                    <div class="slds-p-around_medium lgc-bg">
                        <lightning-input type="text" name="firstName" label="First Name" placeholder="type here..." onchange={handleFormInputChange} required>
                        </lightning-input>
                    </div>

                    <div class="slds-p-around_medium lgc-bg">
                        <lightning-input type="file" label="Attachment" accept="image/png, image/jpg, .zip" onchange={handleFormInputChange}></lightning-input>
                    </div>
</template>

JS file:

    this.firstName;
    this.file;
    handleFormInputChange(event) {

    if(event.target.name == 'firstName'){
       this.firstName = event.target.name;
    }

        if (event.target.files) {
            this.file = event.target.files[0];
        }

        **const data = JSON.stringify({firstName: this.firstName,file: this.file});**
        const nextEvnt = new CustomEvent('initate', {
            detail: { data }
        });
        this.dispatchEvent(nextEvnt);

    }

I tried using below approach that I saw at this link – https://www.salesforcecodecrack.com/2019/06/custom-file-upload-in-lightning-web.html

However, this.fileReader.onloadend gets called only after I form the JSON.

this.fileReader= new FileReader();
// set onload function of FileReader object  
this.fileReader.onloadend = (() => {
    this.fileContents = this.fileReader.result;
    let base64 = 'base64,';
    this.content = this.fileContents.indexOf(base64) + base64.length;
    this.fileContents = this.fileContents.substring(this.content);

    // call the uploadProcess method 
    this.saveToFile();
});

this.fileReader.readAsDataURL(this.file);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to read the file asynchronously, because otherwise the browser would “freeze” while trying to read the file (JavaScript is a single-threaded model by intention, hence the need for asynchronous file reads).

You would end up doing something like this:

export default class MyWebComponentName extends LightningElement {
    async handleFormInputChange(event) {
        if(event.target.files) {
            const fileName = event.target.files[0].name;
            try {
                const fileContent = await this.readFile(event.target.files[0]);
                const initEvent = new CustomEvent(
                    'initate',
                    {
                        detail: {
                            fileName: fileName,
                            body: fileContent
                        }
                    }
                );
                initEvent.fire();
            } catch(error) {
                // Show an error to the user... not a log 😁
                console.log(error);
            }
        }
    }
    readFile(file) {
        return new Promise((resolve, reject) => {
            const fileReader = new FileReader();
            fileReader.onload = () => {
                resolve(fileReader.result.split(/base64,/)[1]);
            };
            fileReader.onerror = () => {
                reject(fileReader.error);
            };
            fileReader.readAsDataURL(file);
        });
    }
}

Notice how I use await to create a promise to read the file, then process the results after the file is read. This is a pretty bare-bones example, but it should get you started. Note that we’re also not handling the possibility of multiple files or other errors, this is just a proof of concept for you to get started with.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x