Thursday, 11 October 2012

Javascript Tricks: Getting the full filepath in Mozilla FF and IE.

During our project, I stumbled upon a problem that seemed unsolveable. I was required to get the full path name:

C:\Documents and Settings\Clare\My Documents\test.jpg

My html code was:

<input id="uploadedFile" name="uploadedFile" type="file" onchange="readFile();">
<input type="hidden" value="" id="uploadFileName"/>

My Javascript/Jquery code:

function readFile() {
    var fullPath = $('#uploadedFile').val();   
    if (fullPath != null) {           
        alert(fullPath );
        $('#uploadFileName').val(fullPath ); //Transfer the file path to hidden field
    }

However, this only works with IE. And we mainly use Firefox. 

In firefox,
The output is: test.jpg
 Note: For security reasons, FF prevents the server to access local information.

In IE, 
The output is: C:\Documents and Settings\Clare\My Documents\test.jpg
which is correct.

I have been searching for the solution for almost 8 hours. I have tried using an applet but it didn't work(Probably done it the wrong way). Until I found this 100% working solution:

I forgot the website, but if you are the owner of this code, pls don't hesitate to send me a msg.

Complete html code: 
<input id="uploadedFile" name="uploadedFile" type="file" onchange="readFile(this);">
<input type="hidden" value="" id="uploadFileName"/>

Code:
<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);
var fullPath = $('#uploadedFileName').val();
alert(fullPath); //fullPath = C:\Documents and Settings\Clare\My Documents\test.jpg
} else {
alert("Not IE or Firefox (userAgent=" + navigator.userAgent + ")");
}
}
//If the browser is Mozilla FF
function readFileFirefox(fileBrowser) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert('Unable to access local files due to browser security settings.');
return;
}
var fileName=fileBrowser.value;
document.getElementById("uploadedFileName").value=fileName;
}
//If the browser is IE
function readFileIE(fileBrowser) {
var fullPath = $('#uploadedFile').val();
if (fullPath != null) {
alert(fullPath ); //fullPath = C:\Documents and Settings\Clare\My Documents\test.jpg
$('#uploadedFileName').val(fullPath );
}
}
</script>










0 comments:

Post a Comment