简体   繁体   English

我可以不使用FileReader文件选择选项来读取文本文件吗

[英]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. 因此,我试图在Visual Studio中的.cshtml按钮上单击.js脚本中的文件。 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? 我想知道的是,是否可以仅将读取的文件直接链接到已知的文件路径,而不必使用FileReader的输入方法? 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. 我有一个.txt文件,其中包含链接的一部分,因此该文件不会在程序中进行硬编码,并且我可以在需要时进行更改。

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: 我希望该代码在单击按钮时转到.js函数(它确实这样做),但是然后读取设置的.txt文件的内容并将其存储在以下命令的filePath变量中:

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

is this possible? 这可能吗?

You can use the XMLHttpRequest to load a text file. 您可以使用XMLHttpRequest加载文本文件。 In the example below the DIV named dummy will receive the loaded text. 在下面的示例中,名为dummyDIV将接收已加载的文本。 But instead you could also place the http.responseText into a var for further processing. 但是,您也可以将http.responseText放入var中以进行进一步处理。

    <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
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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