简体   繁体   中英

Can I read a text file without using the FileReader file choice option

So I am trying to read a file in a .js script on a .cshtml button-click in visual studio. What I would like to know is if it is possible to just link a file read straight to a known file path without having to use the FileReader's input method? I have a .txt file that holds part of a link so that it's not hardcoded in the program and I can go in and change it if I ever need to.

I expect the code to, on the button click, go to the .js function (which it does), but then read the set .txt file's contents and store it in the filePath variable in the following command:

window.open('http://' + filePath + '/', '_blank');

is this possible?

You can use the XMLHttpRequest to load a text file. In the example below the DIV named dummy will receive the loaded text. But instead you could also place the http.responseText into a var for further processing.

    <div id="test">dummy</div>
    <input id="reset" type="button" value="reset" onMouseUp="resetDIV()" />
    <input id="load" type="button" value="load unsafe" onMouseUp="httpRequest('http://yourserver/yourpath/hello.txt')" />
    <input id="load" type="button" value="load safer" onMouseUp="httpRequestByID(1)" />
    const test = document.getElementById('test');
    const http = new XMLHttpRequest();

    function resetDIV() {
       test.innerHTML = 'dummy';
    }

    const httpResult = function() {
      console.log(http);
      test.innerHTML = http.responseText;
    }

    function httpRequest(_url) {
      // hacker unsafe because if a hacker finds a way to add or modify an element in the DOM and call your function with his own injected URL he can look for files you don't want others to see.
      http.open('GET', _url);
      http.onloadend = httpResult;
      http.send();
    }

    function httpRequestByID(_fileNum) {
      // a little safer function it is when the urls are hard typed and you can only reference by a file number
      if((typeof _fileNum)=='number' && _fileNum>0 && _fileNum<3){
         if(_fileNum===1){http.open('GET', 'http://yourserver/yourpath/hello.txt');}
         if(_fileNum===2){http.open('GET', 'http://yourserver/yourpath/other.txt');}
         http.onloadend = httpResult;
         http.send();
      }else{
         alert('httpRequestByID received an invalid argument');
         // nothing more should happen
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM