如何使用Javascript FileReader()打开本地文件 [英] How to open a local file with Javascript FileReader()

查看:447
本文介绍了如何使用Javascript FileReader()打开本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改

I would like to modify this code so that it works with a specific file only, but I can't figure out the correct URL parameter and all the code examples that I've found use a file selection dialog.

<!DOCTYPE html>
<html>
  <head>
    <title>reading file</title>
    <script type="text/javascript">

        var reader = new FileReader();

        function readText(that){

            if(that.files && that.files[0]){
                var reader = new FileReader();
                reader.onload = function (e) {  
                    var output=e.target.result;

                    //process text to show only lines with "@":             
                    output=output.split("\n").filter(/./.test, /\@/).join("\n");

                    document.getElementById('main').innerHTML= output;
                };//end onload()
                reader.readAsText(that.files[0]);
            }//end if html5 filelist support
        } 
</script>
</head>
  <body>
    <input type="file" onchange='readText(this)' />
    <div id="main"></div>
  </body>

当我从以下位置更改代码时,为什么不起作用

Why doesn't it work when I change the code from:

<body>
    <input type="file" onchange='readText(this)' />
    <div id="main"></div>
</body>

收件人:

<body onload="readText('file:///C:/test.txt')">
    <div id="main"></div>
</body>

推荐答案

由于安全限制,浏览器不提供这种功能.您不允许读取本地文件,除非用户不会在文件选择对话框中选择特定文件(或通过拖放操作不执行此操作).这就是所有代码示例都使用文件选择对话框的原因.

Browsers don't give such ability because of security restrictions. You're not allowed to read local files, untill user won't select specific file in file selection dialog (or won't do this with drag-n-drop). That's why all code examples use file selection dialog.

更多详细信息 HTML5是否允许您从浏览器中与本地客户端文件进行交互

这篇关于如何使用Javascript FileReader()打开本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆