3

I am trying to upload multiple files using lightning-input type="file" below is the code.

HTML

 <lightning-input type="file" onchange={handleOnFileUpload} name="uploadFile" multiple label="Attachment">
              </lightning-input>

JS

@track fileData;
    @track attachmentArray = [];
    handleOnFileUpload(event) {
        console.log('event.target.files -->' + event.target.files);
        console.log("handleOnFileUpload response-->" + JSON.stringify(event.target.files));
        var response = event.target.files;
        this.attachmentArray = [];
        for (var i = 0; i < response.length; i++) {
            // alert('i -->' + i);
            const fileName = response[i].name;
            console.log('fileName --->' + fileName);
            var reader = new FileReader();
            reader.onload = function (e) {
                // The file's text will be printed here
                // console.log(e.target.result);
                var base64 = e.target.result;
                // console.log('i -->' + i);
                // console.log('base64 -->' + i + base64);
                this.fileData = {
                    'filename': fileName,
                    'base64': base64
                }
                console.log(this.fileData);
                this.attachmentArray.push(this.fileData);
                console.log(this.attachmentArray); 

                alert('fffffff');
                 
            };
            reader.readAsText(response[i]);
        }

                    uploadAttachment({
                     recId: this.recordId,
                     strBase64Array: this.attachmentArray
                 }).then((result) => {
                     if (result) {
                         this.dispatchEvent(
                             new ShowToastEvent({
                                 title: "Success",
                                 message: "Attachment uploaded Successfully",
                                 variant: "Success",
                             })
                         );
                     } else {
                         this.dispatchEvent(
                             new ShowToastEvent({
                                 title: "Error",
                                 message: "Failed to Upload Attachment1",
                                 variant: "error",
                             })
                         );
                     }
                 }).catch((error) => {
                     this.dispatchEvent(
                         new ShowToastEvent({
                             title: "Error",
                             message: "Failed to Upload Attachment2",
                             variant: "error",
                         })
                     );
                 });


         
    }

In the console it print up to this line console.log(this.fileData); after that it's not executing also no error occurred in the console.

Can any one help me what I am missing in the above code. Thanks in Advance

1
  • Use Screen Flow with File Upload component, simple and easy to customize.
    – Sarvesh
    Feb 3 at 14:47
6

Reading a file is asynchronous. This means that the upload code will happen before the files are read, and there won't be any files to read, so nothing happens. Instead, you need to wait for the files. I'd use a method to read the files that is asynchronous:

  readFile(fileSource) {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      const fileName = fileSource.name;
      fileReader.onerror = () => reject(fileReader.error);
      fileReader.onload = () => resolve({ fileName, base64: fileReader.result.split(',')[1]});
      fileReader.readAsDataURL(fileSource);
    });
  }

And you can then read all the files at once:

  async handleFileChange(event) {
    this.textFiles = await Promise.all(
      [...event.target.files].map(file => this.readFile(file))
    );
    // Here, you can now upload the files to the server //
  }

Once this loop completes, you'll have the completed file array and can do the upload.


Edit: I've created an example script for this question.

In this example, I use readAsDataURL to get the base64-encoded version instead, and I cleaned up the code a bit. However, it is functionally what I was trying to demonstrate.

7
  • readFile function should call onchange in HTML? Feb 3 at 15:47
  • @SFDC_Beginner No, it's a helper method. You would call it from where your code is now. (handleOnFileUpload).
    – sfdcfox
    Feb 3 at 15:49
  • You mean to say that we have to pass event.target.files to readFile from handleOnFileUpload function right? Feb 3 at 15:55
  • @SFDC_Beginner No, you're iterating over the files, and calling an async function for each file.
    – sfdcfox
    Feb 3 at 16:20
  • Okay, But in readFile function expecting the fileSource as parameter, but this parameter value is not used in helper method. Feb 3 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.