2011-12-09 27 views
0

我正在尝试编写一个要下载的文件列表的网页。这些文件与网页一起存储,我希望网页动态列出要下载的文件夹中的所有文件。这样当更多的时候我不需要修改网页。我知道如何使用JavaScript在网页上创建链接,但我需要先使用它来查找文件的名称。如何使用JavaScript访问存储在网站上的其他文件?

我发现一个网站有代码来浏览文件,如文件浏览器的代码,但它只使用一个字符串来存储当前位置。

这是在标题:

<script type="text/javascript"><!-- 

var myloc = window.location.href; 
var locarray = myloc.split("/"); 
delete locarray[(locarray.length-1)]; 
var fileref = locarray.join("/"); 

//--></script> 

这是身体:

<form> 
<input type=button value="Show Files" onClick="window.location=fileref;"> 
</form> 

然而,这并不能真正帮助,因为我想创建下载文件的链接没有文件浏览器。

编辑:

当你举办一个传统的HTML页面上传的HTMLFILE任何图片或内容的页面,你用什么都服务器。 我想使用JavaScript动态链接到网页托管的每个文件。 我想结合这与托管Dropbox公用文件夹中的文件的简单方法来使文件可用。

+0

你到底在问什么?你想在JavaScript中制作一个文件夹中的所有文件的列表吗? – Blender

回答

1

如果你想在服务器上的文件列表,你需要使用服务器端脚本来收集他们的名字:

JS--

//use AJAX to get the list of files from a server-side script 
$.getJSON('path/to/server-side.php', { 'get_list' : 'true' }, function (serverResponse) { 

    //check the response to make sure it's a success 
    if (serverResponse.status == 'success') { 
     var len = serverResponse.output.length, 
      out = []; 

     //iterate through the serverResponse variable 
     for (var i = 0; i < len; i++) { 

      //add output to the `out` variable 
      out.push('<li>' + serverResponse.output[i] + '</li>'); 
     } 

     //place new serverResponse output into DOM 
     $('#my-link-container').html('<ul>' + out.join('') + '</ul>'); 
    } else { 
     alert('An Error Occured'); 
    } 
}); 

PHP--

<?php 

//check to make sure the `get_list` GET variable exists 
if (isset($_GET['get_list'])) { 

    //open the directory you want to use for your downloads 
    $handle = opendir('path/to/directory'); 
    $output = array(); 

    //iterate through the files in this directory 
    while ($file = readdir($handle)) { 

     //only add the file to the output if it is not in a black-list 
     if (!in_array($file, array('.', '..', 'error_log'))) { 
      $output[] = $file; 
     } 
    } 
    if (!empty($output)) { 

     //if there are files found then output them as JSON 
     echo json_encode(array('status' => 'success', 'output' => $output)); 
    } else { 

     //if no files are found then output an error msg in JSON 
     echo json_encode(array('status' => 'error', 'output' => array())); 
    } 
} else { 

    //if no `get_list` GET variable is found then output an error in JSON 
    echo json_encode(array('status' => 'error', 'output' => array())); 
} 
?> 
相关问题