简体   繁体   中英

Reading a local file with javascript

I'm trying to read a local file from my file system using javascript but I just can't get it to work. I've tried the following approaches below:

//Approach 1
function onInitFs(fs) {
        alert(fs.root.fullPath);
        fs.root.getFile('/test.txt', {}, function(fileEntry) {

        // Get a File object representing the file,
        // then use FileReader to read its contents.
        fileEntry.file(function(file) {
           var reader = new FileReader();

           reader.onloadend = function(e) {
             alert(this.result);
           };

           reader.readAsText(file);
        }, errorHandler);

      }, errorHandler);

    }

    //Approach 2
if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
          xmlhttp.open("GET","test.txt",false);
          xmlhttp.send();
          xmlDoc=xmlhttp.responseText;

But for each approach I'm told that the file can't be found. The path for the file itself is "C:\\test.txt". I've tried prepending "file:" to the path but with no success. I've tried each approach on IE, Mozilla and Chrome. I've looked at each of the threads below but still can't find the answer. Any ideas?

xmlhttprequest for local files

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

XMLHttpRequest not working (blank page)

Read file:// URLs in IE XMLHttpRequest

Read a local file using javascript

For Gecko , from MDN

Starting in Gecko 1.9, files are allowed to read only certain other files. Specifically, a file can read another file only if the parent directory of the originating file is an ancestor directory of the target file. Directories cannot be loaded this way, however.

This means an XMLHttpRequest in (eg) Firefox which has an origin of C:\\foo\\bar.html can only access C:\\foo\\x where x is some path.

Other browsers will have similar restrictions or be even more restricted for the file: protocol. It is much easier if you run a server and load from that.

Do not use file:// or any absolute path, you can put your file in server environment, so maybe it will have a path like: localhost:8080/ROOT/test.txt

Because some browsers don't support reading local files with Javascript, only is not security.

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