kevinewing
kevinewing

Reputation: 49

Adding an Event Listener for Uploading a File that 'Fires' every time

I am trying to upload an excel file to my react app. I am using an event listener but it is only "picking up" the data the first time I upload a file. For example, I start my local server and then upload a file, test1.xlsx this works correctly. I then upload a second file, test2.xlsx. This also works. However, now if I try to upload either test1.xslx or test2.xlsx. Nothing will appear in the console. My code is as follows:

const input = document.getElementById('input-data')
    if(input){
        input.addEventListener('change', () => {
            var data = [];
            readXlsxFile(input.files[0]).then((rows) => {
                data.push(rows)
            })
            console.log(data)
        })
    }

I am fairly new to all this so I am not sure if there is an event listener other than 'change' that would be better or if it is something to due with how the browser is storing the data. Let me know!

Upvotes: 0

Views: 2139

Answers (1)

Kevin Ashworth
Kevin Ashworth

Reputation: 643

I've had success with this (only showing skeleton, but using this structure to load images):

<input onInput={onSelectFile} type="file" ... />

and

const onSelectFile = (e) => {
  const onLoadFn = (dataURL) => {
    // processing goes here, maybe something like
    setImage(dataURL);
  };

  if (e.target.files && e.target.files.length > 0) {
    const reader = new FileReader();
    reader.addEventListener("load", () => onLoadFn(reader.result));
    reader.readAsDataURL(e.target.files[0]);
    // setState etc could go here, something like
    setDialogOpen(true);
  }
};

Upvotes: 2

Related Questions