如何使用 HTML 5 FileReader 读取本地文件? [英] How to read local files using HTML 5 FileReader?

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

问题描述

我正在制作一个应用程序,我需要使用 JavaScript 和 HTML 5 读取本地文件,没有任何 <input> 标签或任何用户交互.

I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input> tags or user interaction whatsoever.

在我的研究中,我发现了 SO 中被大量引用的两个教程:

On my research, I found two tutorials that are heavily cited in SO:

但是,有一个问题.这两个教程都需要通过 input 标签进行用户交互,这是一个致命的问题,因为我想自动将文件的内容读入一个字符串.

However, there is a problem. Both of this tutorials require user interaction via the input tag, which is a life killer since I want to read the contents of the file automatically into a string.

到目前为止,我设法获得了以下代码:

So far I managed to get the following code:

let readFile = function(path) {
    let reader = new FileReader();

    reader.onload = function(e) {
        var text = reader.result;
        console.log(text);
    };

    // Read in the image file as a data URL.
    reader.readAsText(MissingFileHandle);
};

但是正如你所看到的,我遗漏了一个重要的步骤,我遗漏了 MissingFileHandle.我的想法是将 path 传递给此方法,因此该方法会将文件作为文本在本地读取并将其打印到控制台,但我无法实现这一点.

But as you can see, I am missing an important step, I am missing MissingFileHandle. My idea would be to pass a path to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.

给定一个相对路径,如何在不使用 <input> 标签的情况下使用 HTML 5 读取文件的内容?

Given a relative path, how can I read the contents of a file using HTML 5 without using <input> tags?

推荐答案

HTML5 fileReader 工具确实允许您处理本地文件,但这些必须由用户选择,您不能在用户磁盘上查找文件.

The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

是否可以在非服务页面上使用 JS/HTML5 FileReader 加载文件?

如何用Javascript打开本地磁盘文件?

如何将值设置为以 HTML 格式输入文件?

Javascript 不使用输入读取文件

这些链接可帮助您找到答案.

These links help you to find answer.

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

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