最简单的方式就是:IE7(8、9)下------工具------Internet选项------安全-----自定义级别------将文件上传到服务器时包含本地目录路径启用 ,然后就可以用fileupload.postfile.filename就可以获取路径了。
今天做一个关于数据库中数据和EXCEL表对比的DEMO,一开始做的是将EXCEL表上传到服务器之后再对比,可是一旦文件多起来对服务器也是一种考验,于是就只在本地对比,然而在本地对比的时候要获取本地路径,一开始以为 fileupload1.postfile.filename可以获取本地路径,可是这个获取的还是文件名称,fileupload中没有获取当前值得属性,于是就想着用javascript去获取,用document.getElementById("fileupload1").value 用debugger调试的时候获取的居然是一个不存在的地址,郁闷了半天就是搞不清楚是什么问题,于是去网上找了一下,才发现,这种方式只在IE6下面有用,因为高版本的浏览器设定为了安全起见,已经不会显示文件路径,于是用下面方法就可以了,
2 var isIE = (document.all) ? true : false ;
3 var isIE7 = isIE && (navigator.userAgent.indexOf( ' MSIE 7.0 ' ) != - 1 );
4 var isIE8 = isIE && (navigator.userAgent.indexOf( ' MSIE 8.0 ' ) != - 1 );
5 var isIE6 = isIE && (navigator.userAgent.indexOf( ' MSIE 6.0 ' ) != - 1 );
6
7 var file = document.getElementById( " fileupload1 " );
8 if (isIE7 || isIE8) {
9 file.select();
10 // 获取欲上传的文件路径
11 var path = document.selection.createRange().text;
12 document.selection.empty();
13 }
14 var filepath = document.getElementById( " fileupload1 " ).value;
15 if (isIE6) {path = filepath; }
但是在火狐下还是没办法获取文件路径,看到网上有人说用getAsDataURL()方法可以获取路径。我测试了一下,用这个方法确实是可以获得路径,但是些路径是被加密过的。于是继续寻找其他方法。。。
火狐下获取上传文件路径的方法,需要先修改设置。在地址栏输入about:config,然后修改signed.applets.codebase_principal_support的键值,将值修改为true。然后再使用如下代码,就可以获得文件路径。
2 netscape.security.PrivilegeManager.enablePrivilege( " UniversalXPConnect " );
3 }
4 catch (e) {
5 alert( ' 请更改浏览器设置 ' );
6 return ;
7 }
8
9 var fname = document.getElementById( " fileupload1 " ).value;
10 var file = Components.classes[ " @mozilla.org/file/local;1 " ]
11 .createInstance(Components.interfaces.nsILocalFile);
12 try {
13 // Back slashes for windows
14 file.initWithPath( fname.replace( / \ // g, "\\\\") );
15 }
16 catch (e) {
17 if (e.result != Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e;
18 alert( ' 无法加载文件 ' );
19 return ;
20 }
21
22 alert(file.path); // 取得文件路径