简体   繁体   English

是否可以使用FileReader读取已经存在的文件?

[英]Is it possible to read an already existing file using FileReader?

I'm trying to read the contents of a text file that I have stored on my (the host's) computer. 我正在尝试读取存储在(主机)计算机上的文本文件的内容。 When I encountered Javascript's FileReader I thought it was the perfect tool for the job. 当我遇到Javascript的FileReader我认为它是完成这项工作的理想工具。 However , every example or question I see online shows how to use it to read files that are being uploaded from the user's computer (and thus they can use the event target to point toward which file they want to read) or they use AJAX (well, at least the XMLHttpRequest object ) to read their own files. 然而每一个 例子 问题, 看到 网上展示了如何使用它来阅读正在从用户的计算机上传的文件(因此他们可以使用事件目标向他们要读的文件点), 或者 他们 使用 AJAX (以及, 至少 XMLHttpRequest的 对象 )来读取自己的文件。

So is it possible to read from local (to the host) files using FileReader? 那么可以使用FileReader从本地(到主机)文件进行读取吗? As I am researching this question it is making me wonder if I am going about this all wrong, but is the only way to use information from a text file on a webpage through AJAX? 当我研究这个问题时,这使我想知道我是否会犯错,但这是通过AJAX使用网页上文本文件信息的唯一方法吗? That seems wrong, it seems like there must be an easier way. 这似乎是错误的,似乎必须有一种更简单的方法。

A FileReader needs a Blob . FileReader需要一个Blob Which is an object representing a binary file in memory. 这是代表内存中的二进制文件的对象。

From where this Blob comes from doesn't really matter, but you need to have it the browser's assigned memory so that FileReader can access it. 这个Blob的来源并不重要,但是您需要让它具有浏览器分配的内存,以便FileReader可以访问它。 FileReader won't download anything by itself. FileReader不会自行下载任何内容。

So if you are talking about a file stored on your server, then the browser has to download it from there to the computer's memory. 因此,如果您正在谈论存储在服务器上的文件,则浏览器必须将文件从那里下载到计算机的内存中。 As to how this can be achieved, there are many ways the most common being AJAX , as long as the data is downloaded from the server and accessible, at least to build a Blob from it, then FileReader will be happy. 至于如何实现,只要从服务器下载数据并且可以访问数据,至少有很多方法可以使用AJAX ,至少要用它来构建Blob,然后FileReader才会高兴。

If you are talking about a file stored on the user's disk, then the browser needs to be granted the permission to access it and load it in its memory, this is usualy done using an <input type="file"> element, since for security reasons, browsers don't give access to the user disk otherwise. 如果您正在谈论存储在用户磁盘上的文件,则需要授予浏览器访问权限并将其加载到其内存中,通常使用<input type="file">元素来完成此操作,因为安全性原因,否则浏览器不会授予对用户磁盘的访问权限。

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

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