Hướng dẫn can javascript access files?

I’m trying to implemennt a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

Nội dung chính

  • Update 30/07/2018 [disclaimer]:
  • Update-2 [disclaimer]:
  • Modern solution:
  • Local AJAX calls in Chrome are not supported due to same-origin-policy.
  • Not the answer you're looking for? Browse other questions tagged javascript file-io xmlhttprequest or ask your own question.
  • How do I read a .txt file in JavaScript?
  • How do I open a file using JavaScript?
  • How do we read and write files in JavaScript?
  • Can JavaScript open a local file?

function readTextFile[] {
  var rawFile = new XMLHttpRequest[];
  rawFile.open["GET", "testing.txt", true];
  rawFile.onreadystatechange = function[] {
    if [rawFile.readyState === 4] {
      var allText = rawFile.responseText;
      document.getElementById["textSection"].innerHTML = allText;
    }
  }
  rawFile.send[];
}

What is going wrong here?

This still doesn’t seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101.

I’ve tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers [especially Chrome]?

ggorlen

36.2k7 gold badges61 silver badges73 bronze badges

asked Jan 21, 2013 at 20:14

3

You need to check for status 0 [as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver]

function readTextFile[file]
{
    var rawFile = new XMLHttpRequest[];
    rawFile.open["GET", file, false];
    rawFile.onreadystatechange = function []
    {
        if[rawFile.readyState === 4]
        {
            if[rawFile.status === 200 || rawFile.status == 0]
            {
                var allText = rawFile.responseText;
                alert[allText];
            }
        }
    }
    rawFile.send[null];
}

And specify file:// in your filename:

readTextFile["file:///C:/your/path/to/file.txt"];

Themroc

4752 silver badges5 bronze badges

answered Jan 21, 2013 at 20:20

Source file

answered Feb 19, 2015 at 15:35

webskywebsky

2,9121 gold badge33 silver badges29 bronze badges

1

This might help,

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest[] : new ActiveXObject["Microsoft.XMLHTTP"];

    xmlhttp.onreadystatechange = function [] {
        if [xmlhttp.readyState == 4 && xmlhttp.status == 200] {
            alert[xmlhttp.responseText];
        }
    }

    xmlhttp.open["GET", "sample.txt", true];
    xmlhttp.send[];

answered Nov 18, 2016 at 15:20

Sameera R.Sameera R.

4,2161 gold badge33 silver badges51 bronze badges

Local AJAX calls in Chrome are not supported due to same-origin-policy.

Error message on chrome is like this: "Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."

This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.

Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.

answered Dec 26, 2018 at 12:12

1

Adding to some the above answers, this modified solution worked for me.


....

let fileInput  = document.getElementById['file-upload-input'];
let files = fileInput.files;

//Use createObjectURL, this should address any CORS issues.
let filePath = URL.createObjectURL[files[0]];

....

function readTextFile[filePath]{
    var rawFile = new XMLHttpRequest[];
    rawFile.open["GET", filePath , true];
    rawFile.send[null];

    rawFile.onreadystatechange = function []{
        if[rawFile.readyState === 4]{
            if[rawFile.status === 200 || rawFile.status == 0]{
                var allText = rawFile.responseText;
                console.log[allText];
            }
        }
    }     
}

answered Dec 31, 2018 at 19:50

FabiiFabii

3,71013 gold badges49 silver badges89 bronze badges

function readTextFile[file] {
    var rawFile = new XMLHttpRequest[]; // XMLHttpRequest [often abbreviated as XHR] is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
    rawFile.open["GET", file, false]; // open with method GET the file with the link file ,  false [synchronous]
    rawFile.onreadystatechange = function []
    {
        if[rawFile.readyState === 4] // readyState = 4: request finished and response is ready
        {
            if[rawFile.status === 200] // status 200: "OK"
            {
                var allText = rawFile.responseText; //  Returns the response data as a string
                console.log[allText]; // display text on the console
            }
        }
    }
    rawFile.send[null]; //Sends the request to the server Used for GET requests with param null
}

readTextFile["text.txt"]; //

Chủ Đề