Javascript, how to read local file?
I try to read a local file from 开发者_开发百科server. I have been "googling" this topic for a while now, and some say it's impossible, others that it can be done. During this search I've found this script:
Read a file using xmlhttprequest
If the HTML file with your javascript app has been saved to disk, this is an easy way to read in a data file. Writing out is more complicated and requires either an ActiveX object (IE) or XPCOM (Mozilla).
fname - relative path to the file
callback - function to call with file text
function readFileHttp(fname, callback) {
xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
}
Return a cross-browser xmlhttp request object
function getXmlHttp() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp == null) {
alert("Your browser does not support XMLHTTP.");
}
return xmlhttp;
}
But I don't know how to use it, and how should callback function look? Could you provide an example code using these functions?
Being able to read a local file from your browser would be a major breach of security - I for one do not like the idea of any site I visit being able to run code in my browser that would read files from my hard drive. Typically ajax requests are limited to the domain from which the page originated. (However, you can get around this to some extent using techniques like JSONP.) Most browsers will not let you read local files even if the page originated from your local filesystem.
The other methods mentioned should allow you to read files from a domain (even if it is localhost), but not from your filesystem directly.
With javascript you can only read files that are publicly exposed on your server. It's similar to opening it in your browser...
I suggest to use jQuery library to do this, ajax request with this are much easier and supported by all major browsers:
http://api.jquery.com/jQuery.get/
for example you can make it like this:
$.get('/content/test.html', function(data) {
alert(data);
});
The below code will browse a file and copy the content to a textarea:
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.\n"
+"name: " + f.name + "\n"
+"type: " + f.type + "\n"
+"size: " + f.size + " bytes\n"
+ "starts with: " + contents.substr(1, contents.indexOf("\n"))
);
document.getElementById('area').value= contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
<textarea rows=20 id="area"></textarea>
Find below the activeX script to read a local file. (works fine in IE).
var fso = new ActiveXObject("Scripting.FileSystemObject");
//specify the local path to Open
var file = fso.OpenTextFile("C:\\your path\\ filename", 1);
var fileContent = file.ReadAll();
file.Close();
//Parse the contents
// ex: if the content is in JSON format
var obj = eval('(' + fileContent+ ')');
for (var i = 0; i < obj.length; i++) {
//Access each element
alert(obj[i].name);
}
The function you pass in as a callback should comprise the code which actually processes the results of your initial ajax call. For example, at its simplest:
alert("RESPONSE: " + xmlhttp.responseText;
However, we need to clarify what you're trying to do: read a file that's stored on the server? If so, that target file has to be accessible from the web (so that you can pass over its URL to your ajax call), else your code simply won't work.
精彩评论