Click to See Complete Forum and Search --> : Retrieving file name with JavaScript
jpfalet
April 19th, 2009, 04:09 PM
Hello,
I have a question. How can I get the name of a file in my website folder using JavaScript in an onClick attribute. Basically, when I click on the button, I need it to get the name of a certain file and copy it to a variable inside another function (I know how to do this, I just need to know how to get the file name).
Thank You,
J-P
PeejAvery
April 20th, 2009, 07:58 AM
What do you mean you need to get the file name? Is it not a static path?
Also...Only through ActiveX can JavaScript read the filesystem. Even then it must have user interaction to be approved. Are you planning to only run this in Internet Explorer?
Xeel
April 24th, 2009, 08:24 PM
1. If you want to read some file on the server where your website really is - you would need some server-side code for this action, php probably would be the easiest solution for this.
Imagine we have 3 files in the same directory: a txt file you want to copy the name of, the main html where the action button resides and an additional php file I called getFileName.php which will do the job of getting the filename. So here it goes:
primary html:<script type="text/javascript" charset="utf-8">
function getFileNameOnServer(ftype){
document.getElementById("ifbox").src = "";
document.getElementById("ifbox").src = "getFileName.php?ftype="+ftype;
}
function getFileNameInWindowsLocally(ftype){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var dir = fso.GetFolder("path_to_directory");
var fc = new Enumerator(dir.Files);
var fname = "";
var s = "";
for (; !fc.atEnd(); fc.moveNext()){
fname = fc.item()+"";
fname = fname.substring(fname.lastIndexOf("\\")+1,fname.length);
if(fname.indexOf("."+ftype)!=-1){
document.getElementById("fnametxt").innerHTML = fname;
}
}
}
</script>
<form>
<input type="button" value="getFNameFromServer" onclick="getFileNameOnServer('txt');" />
<input type="button" value="getFNameWindowsLocally" onclick="getFileNameInWindowsLocally('txt');" />
<p>filename: <span id="fnametxt"></span></p>
</form>
<iframe id="ifbox" style="display:none;" src=""></iframe>
getFileName.php:<?php
$ftype = $_REQUEST["ftype"];
if ($handle = opendir("path_to_directory")) {
while (false !== ($file = readdir($handle))) {
$exists = stripos($file,$ftype);
if($exists !== false){
echo $file;?>
<script type="text/javascript" charset="utf-8">
top.document.getElementById("fnametxt").innerHTML = "<?php echo $file;?>";
</script>
<?php }
}
closedir($handle);
}
?>
2. If it's all supposed to run locally on a client machine - as PeejAvery said you'd need a OS dependant js code to run. In case of Windows it would be ActiveX. Also ActiveX woks for Internet Explorer only.
P.S. I do not work with ActiveX so my appologies to those who think this isn't the best way to filter filenames.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.