Reading a local text file from a local javascript file? - javascript

I'm using the following code to read a local text file from a local Javascript file, but it isn't working:
var txtFile = new XMLHttpRequest();
txtFile.open('GET', fileLocation, true);
The error I get:
XMLHttpRequest cannot load file:///C:/File.txt. Cross origin requests are only supported for HTTP.
Any ideas?

You can not access local resources from javascript,
You should put this file in your site and try to access it via fileLocation like http://mywebsite/File.txt

look at this:
var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}
function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}

Related

How to read a local text file using javascript

I have a button in in view page. On clicking the button an function gets called.In that function am calling another function with location of file as parameter.In the second function i need to read the file specified in the location passed and show the contents in console.What i already tries is below
ReadFile : function(){
this.ReadTextFile("C:\Users\RFRANCIS\Downloads\Inv00008W.txt");
},
ReadTextFile: function(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);
}
But I am getting Access denied error.Please find me to solve this issue or suggest another method.I am testing this in IE11.
In order to access you local drive you need a valid URL for the file which probably looks more like file:///c:/ than what you have but you have a few overlapping issues here:
The url for a local file must start with file:///
You need to understand about escape characters and slashes in Javascript string literals (you need special syntax to express slashes in javascript)
When you fix these you are still going to get CORS security exceptions because (at least chrome) doesn't perceive local files as one domain. (To resolve this you either need to set you chrome up specially or use a proper localhost http-server on your local machine.

How do I read a local text file?

I want to read a local text file automatically whenever my webpage is opened on my computer. How can I do this? I used the following code from one of solutions answered on this site and it says "Access is denied".
<script type="text/javascript">
var fileDisplayArea = document.getElementById('fileText'); //to show output
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;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///Location/fileToBeRead.txt");
</script>
Is there any other solution to this problem?
You cannot read file off a persons local machine.
You can only read files from the same domain that your site is running on (or if using jsonp to get past XSS rules)
You might be able to use the Local Storage feature of HTML5 to do this.
For security, natively there's no method to read system files (from URL... file:///...).
You should not be reading files on a client machine. Its a security issue and hence not allowed (access denied).
If you want to store data on client machine use cookies rather or as correctly pointed out use a html session or local storage.

How can I read and write XML file with JavaScript in my cordova app?

I use Visual Studio 2013 and Visual Studio Tools for Apache Cordova to build my android app with HTML5 and JavaScript.
I stored a xml file into the res folder: /res/xml/myFile.xml.
Now I simply want to read and write the content in this xml file.
Through the VS-plugin manager I already added the File plugin to the config.xml, which added <vs:plugin name="org.apache.cordova.file" version="1.3.1" />
I already searched for tutorials like on Android Developers, but not for my situation with above mentioned IDE.
So how can I read and write XML file with JavaScript in my cordova app?
I suggest you store your xml inside a javascript variable.
var xmlvar = "<xml><item name='name1' value='value1' />....</xml>"
And then parse it:
$('item', xmlvar).each(function(i) {
//do something - maybe: var itemname = $(this).attr("name");
});
You can't get it from res folder but if you have it outside in /xml/myFile.xml then you can do this to get the file:
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function (e) {
// parse and use xml here, for example:
e.target.responseXML; // or responseText
});
xhr.open('GET', 'xml/myFile.xml', true);
xhr.send();

Load local xml file using javascript in Google Chrome

I think until v5 of Google Chrome the below code worked. Now in the latest version I get the following error when opening my webpage locally:
"XMLHttpRequest cannot load file:///C:/Temp/Course.xml. Cross origin requests are only supported for HTTP."
The Javascript code:
function getXmlDocument(sFile) {
var xmlHttp, oXML;
// try to use the native XML parser
try {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", sFile, false); // Use syncronous communication
xmlHttp.send(null);
oXML = xmlHttp.responseXML;
} catch(e) {
// can't use the native parser, use the ActiveX instead
xmlHttp = getXMLObject();
xmlHttp.async = false; // Use syncronous communication
xmlHttp.resolveExternals = false;
xmlHttp.load(sFile);
oXML = xmlHttp;
}
// return the XML document object
return oXML;
}
// get the best ActiveX object that can read XML
function getXMLObject() {
// create an array with the XML ActiveX versions
var aVersions = new Array("Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0");
// loop through the array until we can create an activeX control
for (var i=0; i<aVersions.length; i++) {
// return when we can create the activeX control
try {
var oXML = new ActiveXObject(aVersions[i]);
return oXML;
}
catch(e) {
}
}
// could not create an activeX, return a null
return null;
}
I really don't want to be forced to open the web page from a web server every time.
Local file access is disabled by default for security reasons. Try starting Google Chrome from the command line with the argument --allow-file-access
It would be more secure if you just start a local webserver and fetch your html and xml from localhost.
You can easily avoid deploying of the files by just let the server serve the contents of a local folder in which you place your xml.
This way you avoid
having to start chrome in an unsecure mode
having problems when you later deploy your app to a server on the internet
server to go is an example for an easy to install webserver http://www.server2go-web.de/

How to load local JSON files in Javascript

I'm writing a web app (well, actually it will eventually be an OS X Dashboard widget, but I decided to prototype it first as a simple web page) that needs to load some initializing data from a local JSON file. My code looks like this:
function loadDatos() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'datos.json', true);
xobj.onReadyStateChange = function () {
if (xobj.readyState == 4) {
var jsonTexto = xobj.responseText;
ProcessTheData(jsonTexto);
}
}
xobj.send(null);
}
The function get called from an onLoad() event in the HTML file's BODY tag. Now, from what I see when debugging, the function gets executed, but the onReadytStateChange event handler never gets called.
What should I do? I thought it was a bit odd to use a XMLHttpRequest to access a local file, but the new tutorials I've seen that deal with this issue seem to say that it should work (the 99% of docs I've seen talk about how to load JSON from a remote server, not from a local file).
I'm testing using Firefox 3.6.10, but I've also tried with Safari 4.
onreadystatechange property has no capital letters. See: MDC XMLHttpRequest
Unless we add extension .json and MIMETYPE application\json, IIS will throw an error.
See here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true

Categories

Resources