firefox3不能获得html file的全路径的问题

26 篇文章 0 订阅
26 篇文章 0 订阅

 遇到这个问题以后,在往上 找了以下,发现这个大哥的博客写的很详细,于是就转载下来,以供参考!原文网址是:http://www.cnblogs.com/jaxu/archive/2009/04/19/1439016.html    下面是转载的正文:

 

     相信很多人都使用过<input type="file"/>这样的HTML控件,它看起来非常普通,是我们在做Web应用程序中用于上传客户端本地文件时不可缺少的控件,然而最近 我发现这个控件在最新的FireFox浏览器(或者最新的IE8中也会存在这个问题,我没有尝试过,读者可以试一下)中却失去了效果,导致我们在通过这个 控件的value属性得到的值中只包含了文件名而没有文件路径,这个在IE7中是可以正常获取到全文件名的(即文件完整路径+文件名)。IE7和大部分当 前流行的浏览器(如FireFox2版本)都可以获取到文件的路径,但是FireFox3却不行,我查了很多资料,发现这是FireFox3为了弥补在低 版本中可能会引起安全问题的一个漏洞,据说黑客会通过FireFox的这一安全隐患向服务器上传文件!其实我也搞不懂,不就是本地文件的路径么?怎么会影 响到服务器的安全问题呢?看来高手们还真的很强!!

    来说说我为什么要得到本地所选的文件的路径。大家都知道163邮箱,里面在上传邮件附件的时候是允许选择多附件的,我要做的功能类似于这个,不过我在这里 并不是要研究163是如何实现这个功能,我只想在用户选择文件的时候动态在一个Div中添加他所选择的文件的信息和一个删除按钮,然后将这个文件的信息保 存在页面的一个隐藏域中,当用户保存页面时服务器端代码根据页面隐藏域中的信息将用户所选的文件上传到服务器上。当然,页面隐藏域中的信息至少要包含用户 本地所选文件的路径,否则就不知道在什么地方去找文件了。有关如何实现动态添加HTML节点不是本文的重点,这里我也不贴代码了,下面说说我所遇到的问 题。

    下面是一段用于测试问题的代码。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
</head>
<body>
    <input id="File1" type="file" /><input id="btAdd" type="button" value="Add" οnclick="alert(document.getElementById('File1').value);" />
</body>
</html>

 运行后在IE7中的结果:



 运行后在FireFox3中的结果:.


那么我如何才能在FireFox3中取得本地文件的路径呢?就像上面我在IE7中得到的那个值一样!暂且撇开这个问题,先说说在FireFox3中如何上 传一个文件吧。既然FireFox3中将获取本地文件的路径的方法当做一个安全隐患被禁止了,那么它一定有相关的方法来解决这个问题,否则 FireFox3就不能实现在客户端上传文件的功能了,就像前两天我的一个同事说的一样,要真是这样,FireFox就废了!其实FireFox3中引入 了一个新的接口用来解决这个问题,那就是nsIDOMFile,它专门被用来从客户端的input type="file"的控件中获取文件数据,这样就可以将本地的文件保存到服务器上。这是一个非常好的解决办法,以至于我们在FireFox3中开发这 样的应用程序时比先前简单获取value值然后再通过服务器端代码上传文件要简单许多,不过令人担忧的是,这个接口只适用于FireFox,在IE和其它 的浏览器中并不支持。一会儿再说如何解决浏览器的兼容性问题,先看一下在FireFox3中怎么使用nsIDOMFile。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>input type=file & Firefox 3</title>
</head>

<body>
    
<h1>input type=file & Firefox 3</h1>
    
<script type="text/javascript">
// <![CDATA[

function inputFileOnChange() {    
    if(document.getElementById('my-file').files) {
        // Support: nsIDOMFile, nsIDOMFileList
        alert('value: ' + document.getElementById('my-file').value);
        alert('files.length: ' + document.getElementById('my-file').files.length);
        alert('fileName: ' + document.getElementById('my-file').files.item(0).fileName);
        alert('fileSize: ' + document.getElementById('my-file').files.item(0).fileSize);
        alert('dataurl: ' + document.getElementById('my-file').files.item(0).getAsDataURL());
        alert('data: ' + document.getElementById('my-file').files.item(0).getAsBinary());
        alert('datatext: ' + document.getElementById('my-file').files.item(0).getAsText("utf-8"));
    };
};

// ]]>
</script>
    
<div>
    <input type="file" name="my-file" id="my-file" οnchange="inputFileOnChange();" />
</div>
    
</body>
</html> 
 

document.getElementById('my-file').files方法用于获取到用户所选择的文件的集合,一般情况下都是选择单 一文件(貌似FireFox这样做是支持多文件选择的,不过没有试过,读者可以自己去尝试),item数组可以得到其中的某一个文件,然后我们就可以使用 nsIDOMFile所提供的属性和方法了。它包括2个属性和3个方法:

fileName :用于获取到用户所选文件的名称,这和直接取value值所得到的结果一样。

fileSize :得到用户所选文件的大小。

getAsBinary() :得到用户所选文件的二进制数据。

getAsDataURL() :得到用户所选文件的路径,该路径被加密了,目前只能在FireFox中使用。

getAsText() :得到用户所选文件的指定字符编码的文本。

    读者可以参考这个地址:https://developer.mozilla.org/en/nsIDOMFile

    有一点需要说明,方法getAsDataURL()可以取得用户所选文件的本地路径,但是这个路径的字符串文本被FireFox加密了,并且这段密文只能 被FireFox识别,其它的浏览器不能识别,也就是说我将被加密后的路径直接赋值给一个img标签的src属性,在FireFox中是可以直接显示出图 片的,而在IE中却不行。从这一点来看,FireFox是不是有点王者风范呢?居然连大名鼎鼎的IE都不支持!

    再回到本文一开始所提的那个问题上来。即然我不能在FireFox中得到用户所选文件的本地路径,而且采用getAsDataURL()方法得到的这个路 径也不能体现通用性,那怎么才能彻底解决这个问题呢?简单思考一下,浏览器为什么能够调用OS的文件打开对话框,从而进一步得到用户所选的文件的信息呢? 浏览器不是仅仅只能解释HTML文本么?没错,这个是浏览器的基本功能,至于如果调用OS提供的功能接口,那是浏览器的各个不同厂商自己要做的工作,这个 似乎没有一个统一的标准,也不会被列入到W3C的规范中,FireFox3就是一个特例。这样看来,我们只有自己编写代码来调用OS的文件打开对话框了, 这看起来是一件非常辛苦的事情,最好的办法莫过于编写ActiveX控件嵌入到浏览器中来执行,幸运的是IE和FireFox都提供了现成的方法供我们调 用,我们只需要在js脚本中调用即可。当得知这一点时,我差点高兴得一晚上没有睡觉。

    好了,现在来看我是怎么做的了!

 

<html>
<head>
    <title>Untitled Page</title>

    <script type="text/javascript">
function readFile(fileBrowser) {
    if (navigator.userAgent.indexOf("MSIE")!=-1)
        readFileIE(fileBrowser);
    else if (navigator.userAgent.indexOf("Firefox")!=-1 || navigator.userAgent.indexOf("Mozilla")!=-1)
        readFileFirefox(fileBrowser);
    else
        alert("Not IE or Firefox (userAgent=" + navigator.userAgent + ")");
}

function readFileFirefox(fileBrowser) {
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } 
    catch (e) {
        alert('Unable to access local files due to browser security settings. To overcome this, follow these steps: (1) Enter "about:config" in the URL field; (2) Right click and select New->Boolean; (3) Enter "signed.applets.codebase_principal_support" (without the quotes) as a new preference name; (4) Click OK and try loading the file again.');
        return;
    }

    var fileName=fileBrowser.value;
    var file = Components.classes["@mozilla.org/file/local;1"]
        .createInstance(Components.interfaces.nsILocalFile);
    try {
        // Back slashes for windows
        file.initWithPath( fileName.replace(/\//g, "\\\\") );
    }
    catch(e) {
        if (e.result!=Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e;
        alert("File '" + fileName + "' cannot be loaded: relative paths are not allowed. Please provide an absolute path to this file.");
        return;
    }

    if ( file.exists() == false ) {
        alert("File '" + fileName + "' not found.");
        return;
    }
    alert(file.path); // I test to get the local file's path.
    var is = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance( Components.interfaces.nsIFileInputStream );
    try { is.init( file,0x01, 00004, null); }
    catch (e) {
        if (e.result!=Components.results.NS_ERROR_FILE_ACCESS_DENIED) throw e;
        alert("Unable to access local file '" + fileName + "' because of file permissions. Make sure the file and/or parent directories are readable.");
        return;
    }
    var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance( Components.interfaces.nsIScriptableInputStream );
    sis.init( is );
    var data = sis.read( sis.available() );

    alert("Data from file: " + data); // I test to get the local file's data.
}

function readFileIE(fileBrowser) {
    var data;
    try {
        var fso = new ActiveXObject("Scripting.FileSystemObject");

        var fileName=fso.GetAbsolutePathName(fileBrowser.value);
        if (!fso.FileExists(fileName)) {
            alert("File '" + fileName + "' not found.");
            return;
        }

        var file = fso.OpenTextFile(fileName, 1);

        data = file.ReadAll();
        alert("Data from file: " + data);
        file.Close();
    }
    catch(e) {
        if (e.number == -2146827859) {
            // This is what we get if the browser's security settings forbid
            // the use of the FileSystemObject ActiveX control
            alert('Unable to access local files due to browser security settings. To overcome this, go to Tools->Internet Options->Security->Custom Level. Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
        }
        else if (e.number == -2146828218) {
            // This is what we get if the browser can't access the file
            // because of file permissions
            alert("Unable to access local file '" + fileName + "' because of file permissions. Make sure the file and/or parent directories are readable.");
        }
        else throw e;
    }
}
    </script>

</head>
<body>
    <form name="form1">
    Browse to select a file
    <input type="file" name="fileBrowser" size="125" οnchange="readFile(this)" />
    </form>
</body>
</html>

 首先我们需要判断用户浏览器的类型来选择执行不同的function,IE中直接调用Scripting.FileSystemObject这个 ActiveXObject,不过如果用户的IE没有打开“对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本”的话是不能执行这行代码的, 在脚本中给出了提示,告诉用户必须将这个选项打开。

 IE的问题不大,因为我们完全可以直接使用input的value值得到文件的路径,这里给出的方法主要是可以得到文件的二进制数据,重点看看在 FireFox3中是如何做的。FireFox3中需要用户在配置页面中添加一个名称为 signed.applets.codebase_principal_support的键值,将值设为true,然后就可以通过代码中给出的方法得到文 件的本地路径了,同样也可以得到文件的二进制数据。

 

   这样,我的问题就可以解决了,不管是在IE中,还是在FireFox中,我都可以获取到用户所选文件的本地路径,然后保存在页面的隐藏域中,当用户提交页面时,服务器端代码便可以通过页面隐藏域中的值得到用户所选择的文件的路径,从而上传文件到服务器。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值