Javascript,如何读取本地文件? [英] Javascript, how to read local file?

查看:294
本文介绍了Javascript,如何读取本地文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从服务器读取本地文件。我一直在谷歌搜索这个话题已有一段时间了,有些人说这是不可能的,有些人则说可以做到。在此搜索过程中,我找到了这个脚本:

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:


使用xmlhttprequest读取文件

Read a file using xmlhttprequest

如果带有javascript应用程序的HTML文件已保存到磁盘,
这是一种读取数据文件的简便方法。写出是
更复杂,需要一个ActiveX对象(IE)
或XPCOM(Mozilla)。

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 - 文件的相对路径

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);

}




返回跨浏览器xmlhttp请求对象

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?

推荐答案

能够从浏览器中读取本地文件将是一个重大漏洞安全性 - 我不喜欢我访问的任何网站的想法,能够在我的浏览器中运行代码,从我的硬盘读取文件。通常,ajax请求仅限于页面所源自的域。 (但是,您可以使用JSONP等技术在某种程度上解决这个问题。)即使页面来自本地文件系统,大多数浏览器也不会让您读取本地文件。

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.

提到的其他方法应该允许您从域中读取文件(即使它是localhost),但不能直接从您的文件系统读取。

The other methods mentioned should allow you to read files from a domain (even if it is localhost), but not from your filesystem directly.

这篇关于Javascript,如何读取本地文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆