Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...