天天看點

JS擷取上傳檔案的絕對路徑,相容IE和FF

<input type="file" id="fileBrowser" name="fileBrowser" size="50" onchange="readFile(this)" />

<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) { //FF浏覽器

    try { 

        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 

    }  

    catch (e) { 

        alert('路徑錯誤!'); 

        return; 

    }

    var fileName=fileBrowser.value; 

    var file = Components.classes["@mozilla.org/file/local;1"] 

        .createInstance(Components.interfaces.nsILocalFile); 

    try { 

        file.initWithPath( fileName.replace(///g, "\\") ); 

    } 

    catch(e) { 

        if (e.result!=Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e; 

        return; 

    }

    if ( file.exists() == false ) { 

        alert("File '" + fileName + "' not found."); 

        return; 

    } 

    alert(file.path); 

}

function readFileIE(fileBrowser) { //IE浏覽器,可直接擷取上傳檔案路徑

    alert(document.getElementById("fileBrowser").value);

</script>