0

I am trying to create a promise that I can call that will extract the contents of the file and retrieve it but having trouble setting it up.

performJrflUpload() : Promise<String> {   

return new Promise((resolve, reject) => {
  var tempFileName: string;     
  let input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xml';    
  input.addEventListener("change", function() {
    const file = this.files[0];
    tempFileName = this.files[0].name;
    var fr = new FileReader();
    fr.readAsText(file, "UTF-8");   
    fr.onload = async function (evt) {
      let result = await evt.target.result.toString();            
      resolve(result);
    };
    input.click();    
  })
});

} `

My attempts to call this method have failed. I think because my promise is not set up right. But all I really want to do is create an input (OpenFileDialog in C# lingo) and get the contents of a file wrapped in a promise.

  • I wouldn't be surprised if browsers disallow programmatically clicking a file input for security reasons. [More on that here](https://stackoverflow.com/q/210643/328193). – David Aug 29 '23 at 20:34
  • Seems to work, hopefully no time soon! – John Grove Aug 29 '23 at 20:56

1 Answers1

1

Try this updated code:

performJrflUpload(): Promise<string> {
  return new Promise((resolve, reject) => {
    let input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xml';

    input.addEventListener("change", function() {
      const file = this.files[0];
      if (!file) {
        reject(new Error("No file selected"));
        return;
      }

      var fr = new FileReader();
      fr.readAsText(file, "UTF-8");

      fr.onload = function(evt) {
        resolve(evt.target.result.toString());
      };

      fr.onerror = function() {
        reject(new Error("Error reading file"));
      };
    });

    input.click();
  });
}