简体   繁体   English

如何在 javascript 中制作可以直接读取任何文件并用现有文本替换自身的 function?

[英]How to make a function that can directly read any file and replace itself with the text present, in javascript?

I have a html file named main.html and here is it's source:我有一个名为main.html的 html 文件,这是它的来源:

<!DOCTYPE html>
<html>
<head>
<script>
  var openFile = function(event) {
    var input = event.target;

    var reader = new FileReader();
    reader.onload = function(){
      var text = reader.result;
      var node = document.getElementById('output');
      node.innerText = text;
      console.log(reader.result.substring(0, 200));
    };
    reader.readAsText(input.files[0]);
  };
</script>
</head>
<body>
<input type='file' onchange='openFile(event)'><br>
<div id='output'>
...
</div>
</body>
</html>

In the above markup, I used an input to select files while being in the webpage after load.在上面的标记中,我在加载后在网页中时使用了 select 文件的输入。 After I selected my file, the source of the file is inherited in the div with id output .在我选择了我的文件后,文件的源被继承在 div 中,id为 output But I don't want to select the file in such a way.但我不想以这种方式 select 文件。 Being new to FileLoader() , I am not understanding what to do,!作为FileLoader()的新手,我不明白该怎么做! So, lets consider a function named as Reader() , and we can go with it something like this:因此,让我们考虑一个名为Reader()的 function ,我们可以使用 go 像这样:

 document.getElementById("output").innerText = Reader("file://pathtofilerequired/anyfile.anyextension");

Thus after the Reader() function will read the file, with respect to the source given, it will replace itself with the text or anything present in the file.因此,在Reader() function 将读取文件之后,相对于给定的源,它将用文本或文件中存在的任何内容替换自身。 So can this Reader() function be made?那么这个Reader() function 可以制作吗? Thanks for your time.谢谢你的时间。

if the file is on your server you can use the following:如果文件在您的服务器上,您可以使用以下内容:

jQuery.get('your_file.txt',function(data){
   document.getElementById("output").innerText = data;
});

If you want to pull in from your local system you'll need an upload mechanism in place first.如果你想从你的本地系统中提取,你首先需要一个上传机制。

$.ajax({
    url: "your_file.txt",
    async: false,
    success: function(data){ 
        document.getElementById("output").innerText = data;
    }
});

Uploadind must be realized with backend script. Uploadind 必须通过后端脚本来实现。

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

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