0

I want to upload a text file on a webpage, read it, and then in javascript do some computation on the content of the file, e.g by calling a function called:

  do_calculation().

Here is the code I have so far. But it is not complete as I don't know how to read the content of the file from: function do_calculation().

html code:

  <tr>
  <td>Select a File to Load:</td>
  <td><input type="file" id="pubkey"></td>
  <output id="result" />
  <td><button onclick="loadFileAsText()">Load Selected File</button><td>
  </tr>

Javascript code:


 <script type="text/javascript">


function loadFileAsText(){
  var fileToLoad = document.getElementById("pubkey").files[0];

  var fileReader = new FileReader();
  fileReader.onload = function(fileLoadedEvent){
       var textFromFileLoaded = fileLoadedEvent.target.result;
      document.getElementById("result").value = textFromFileLoaded;
  };

   fileReader.readAsText(fileToLoad, "UTF-8");


  }

   function do_calculation(){

   }

   </script>

Moreover, I'd like to know how I can work on two uploaded files.

1
  • so in the onload function call the function and pass in the content.... Commented Nov 1, 2019 at 16:06

1 Answer 1

1

Just call your do_calculation() function in your filereader.onload fucntion and give it the parameter of the text. Then you can do whatever you want with the text at that point within your do_calulation() function

Jsfiddle: https://jsfiddle.net/yxmngk0r/

Hopefully this helps.

Sign up to request clarification or add additional context in comments.

9 Comments

thanks for the answer, can you also give me a hint on how to upload two files and work on both?
No problem glad I could help. If I solved the answer to this question, please mark as the accepted answer and ask a new question about how to upload two files, I'll be glad to help on that problem as well. It just needs to be a separate question so this question can be resolved.
Ah ok. Well what is the question for the two file upload problem you're having?
Assume i upload two files. I want to read the content of both and then I call again do_calculation() function to do some computation- for instance one file is for public key and the other one is for signature and do_calculation() wants to verify the signature using the public key
or even simpler, one file contains value 1 and the other file contains value 2, the do_calculation function wants to do 1+2.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.