如何使用JavaScript访问存储在网站上的其他文件

How do you access other files stored on an website with JavaScript?

本文关键字:其他 文件 网站 何使用 JavaScript 访问 存储      更新时间:2023-09-26

我正试图为下载的文件列表编写一个网页。文件与网页存储,我希望网页能够动态列出文件夹中下载的所有文件。这样,当更多的添加,我不必修改网页。我知道如何使用JavaScript在网页上创建链接,但我需要使用它来找到文件的名称。

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

在header中:

<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公共文件夹中托管文件相结合,以一种简单的方式使文件可用。

如果需要服务器上的文件列表,则需要使用服务器端脚本收集它们的名称:

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()));
}
?>