日期:2014-05-16  浏览次数:20394 次

JS获取表单里文件选择框的文件路径

表单代码

<form name="myexcel" action="" enctype="multipart/form-data" method="post">
<table width="800" border="1" align="center">
  <tr>
    <td width="213" align="right" >inputFile位置:</td>
    <td width="661"><input type="text" size="60" name="toDir" id="toDir" />
        <input type="button" onclick="javascript:inputDir();" value="JS获取" />
    </td>
  </tr>
  <tr>
    <td align="right">导入文件:</td>
    <td><input type="file" id="path" name="path" size="60" /></td>
  </tr>
  <tr>
    <td colspan="2"><input type="submit" value="整理" name="button1" /></td>
  </tr>
</table>
</form>

?JS代码

function getFilePath(filePathId){
    //判断浏览器类型
    var isIE = (document.all) ? true : false;
    var isIE7 = isIE && (navigator.userAgent.indexOf('MSIE 7.0') != -1);
    var isIE8 = isIE && (navigator.userAgent.indexOf('MSIE 8.0') != -1);	
    var path = '';
    if(isIE7 || isIE8)
    {
        var file = document.getElementById(filePathId);
        file.select();
        path = document.selection.createRange().text;
        document.selection.empty();
    }else{
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        }catch (e) {
            alert('在地址栏输入about:config,然后修改signed.applets.codebase_principal_support的键值,将值修改为true');
            return;
        }
        
        var fname = document.getElementById(filePathId).value;
        var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        try {
            // Back slashes for windows
            file.initWithPath( fname.replace(/\//g, "\\\\") );
        }catch(e) {
            if (e.result!=Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e;
            alert('无法加载文件');
            return;
        }
        path = file.path;
    }
    return path;
}
function inputDir(){
	var path = getFilePath('path');
    document.getElementById("toDir").value = path;
}
?
1 楼 dingherry 2012-05-28  
试了下直接.value是,只能得到文件名。
LZ 能获得绝对路径了