Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract a Promise from FileReader.onload

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading