简体   繁体   中英

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. 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.

So is it possible to read from local (to the host) files using 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? That seems wrong, it seems like there must be an easier way.

A FileReader needs a 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. FileReader won't download anything by itself.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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