如何读取本地文本文件?

本文探讨了解决XMLHttpRequest异常101的方法,详细解释了如何在不同浏览器(包括Chrome和Firefox)中正确读取本地文本文件。通过调整代码并使用特定的文件路径格式,可以确保跨浏览器的兼容性。

本文翻译自:How to read a local text file?

I'm trying to write a simple text file reader by creating a function that takes in the file's path and converts each line of text into a char array, but it's not working. 我正在尝试通过创建一个接受文件路径并将文本的每一行转换为char数组的函数来编写一个简单的文本文件阅读器,但是它不起作用。

function readTextFile() {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "testing.txt", true);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      var allText = rawFile.responseText;
      document.getElementById("textSection").innerHTML = allText;
    }
  }
  rawFile.send();
}

What is going wrong here? 这是怎么了?

This still doesn't seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101. 以前的版本中稍稍更改了代码后,这似乎仍然不起作用,现在它给了我一个XMLHttpRequest异常101。

I've tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)? 我已经在Firefox上对其进行了测试,并且可以运行,但是在Google Chrome中它无法正常工作,并且一直给我一个异常101。如何使它不仅可以在Firefox上而且还可以在其他浏览器(尤其是Chrome)上运行)?


#1楼

参考:https://stackoom.com/question/ycBD/如何读取本地文本文件


#2楼

You need to check for status 0 (as when loading files locally with XMLHttpRequest , you don't get a status returned because it's not from a Webserver ) 您需要检查状态0(如使用XMLHttpRequest在本地加载文件时,不会返回状态,因为它不是来自Webserver

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

And specify file:// in your filename: 并在文件名中指定file://

readTextFile("file:///C:/your/path/to/file.txt");

#3楼

Try creating two functions: 尝试创建两个函数:

function getData(){       //this will read file and send information to other function
       var xmlhttp;

       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();               
       }           
       else {               
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
       }

       xmlhttp.onreadystatechange = function () {               
           if (xmlhttp.readyState == 4) {                   
             var lines = xmlhttp.responseText;    //*here we get all lines from text file*

             intoArray(lines);     *//here we call function with parameter "lines*"                   
           }               
       }

       xmlhttp.open("GET", "motsim1.txt", true);
       xmlhttp.send();    
}

function intoArray (lines) {
   // splitting all text data into array "\n" is splitting data from each new line
   //and saving each new line as each element*

   var lineArr = lines.split('\n'); 

   //just to check if it works output lineArr[index] as below
   document.write(lineArr[2]);         
   document.write(lineArr[3]);
}

#4楼

可能您已经尝试过,键入“ false”,如下所示:

 rawFile.open("GET", file, false);

#5楼

other example - my reader with FileReader class 另一个例子-我的FileReader类的阅读器

<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
    </head>
    <body>
        <script>
            function PreviewText() {
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
            oFReader.onload = function (oFREvent) {
                document.getElementById("uploadTextValue").value = oFREvent.target.result; 
                document.getElementById("obj").data = oFREvent.target.result;
            };
        };
        jQuery(document).ready(function(){
            $('#viewSource').click(function ()
            {
                var text = $('#uploadTextValue').val();
                alert(text);
                //here ajax
            });
        });
        </script>
        <object width="100%" height="400" data="" id="obj"></object>
        <div>
            <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
            <input id="uploadText" style="width:120px" type="file" size="10"  onchange="PreviewText();" />
        </div>
        <a href="#" id="viewSource">Source file</a>
    </body>
</html>

#6楼

Visit Javascripture ! 访问Javascripture And go the section readAsText and try the example. 然后进入readAsText部分并尝试示例。 You will be able to know how the readAsText function of FileReader works. 您将能够知道FileReaderreadAsText函数如何工作。

    <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' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    ...
    </div>
    </body>
    </html>
### 三级标题:在 uni-app H5 开发中如何访问和读取手机本地存储的文件 在 uni-app 开发中,H5 页面运行于浏览器环境中,由于浏览器的安全策略限制,无法直接访问手机本地存储的文件系统。若需实现文件读取功能,通常需要借助 HTML5 提供的 `<input type="file">` 元素让用户主动选择文件进行读取。 以下是一个使用 `<input>` 标签读取本地文件内容的示例代码: ```html <template> <view> <input type="file" @change="handleFileChange" /> </view> </template> <script> export default { methods: { handleFileChange(event) { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = function(e) { const content = e.target.result; console.log('文件内容:', content); }; reader.readAsText(file); } } }; </script> ``` 上述代码中,通过 `<input type="file">` 元素触发 `@change` 事件,获取用户选择的文件对象,再使用 `FileReader` 读取文件内容并输出到控制台。此方法适用于文本文件读取,若需处理二进制文件,则可使用 `readAsArrayBuffer` 方法。 若项目基于 uni-app 并需要访问更底层的文件系统(如 Android/iOS 原生文件系统),则应使用 `plus.io` 或 `uni.downloadFile` 和 `uni.saveImageToPhotosAlbum` 等 API 进行操作。例如,读取或写入文件前需要在 `manifest.json` 中配置权限,并在运行时请求访问权限: ```json <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` 请求权限的代码示例如下: ```javascript plus.android.requestPermissions([ 'android.permission.WRITE_EXTERNAL_STORAGE', 'android.permission.READ_EXTERNAL_STORAGE' ], (e) => { // 权限请求成功 }, (v) => { // 权限请求失败 }); ``` 完成权限请求后,可使用 `plus.io` 模块读取或写入文件: ```javascript const rootPath = plus.io.convertLocalFileSystemURLToPath('file:///storage/emulated/0/'); console.log('设备存储根路径:', rootPath); ``` 以上方法适用于 uni-app 中的原生应用开发(如打包成 APK 或 IPA 文件),但在 H5 环境下无法直接访问本地文件系统,只能通过用户交互选择文件的方式进行读取。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值