answered Feb 19, 2015 at 15:35
webskywebsky
2,9421 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,74013 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"]; //