首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用js对所有文件夹和文件进行迭代以获得列表

使用js对所有文件夹和文件进行迭代以获得列表
EN

Stack Overflow用户
提问于 2022-04-09 13:04:07
回答 1查看 235关注 0票数 1

我需要通过迭代指定父文件夹中的所有文件夹来获得所有文件的列表。我听说递归是最好的实现方法,但我不确定如何使用递归来使用Dropbox获取文件夹中的文件列表。

下面的代码可以很好地获取单个文件夹中的文件,我希望修改代码,这样它就可以递归地获取文件。

代码语言:javascript
复制
<!doctype html>
<html>
<head>
  <title>Dropbox JavaScript SDK</title>
<style>
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  line-height: 1.5;
}
.container {
  display: block;
  width: 90%;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}
.container.main {
  padding-top: 30px;
}
code, .code {
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  color: #666;
}
.info {
  font-size: 13px;
  font-style: italic;
  color: #666;
  margin-top: 40px;
}
a {
  color: #007ee5;
}
input {
  border: 2px solid #007ee5;
  border-radius: 3px;
  padding: 8px;
  font-size: 16px;
}
.button, button {
  border-radius: 3px;
  background-color: #007ee5;
  border: none;
  color: #fff;
  font-size: 16px;
  padding: 10px 15px;
  text-decoration: none;
}

.page-header {
  background-color: #007ee5;
  padding: 10px 0 0 0;
}
.page-header .container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 150px;
}
.page-header a {
  color: #fff;
  text-decoration: none;
}
.page-header nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.page-header h1 {
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 17px;
  font-weight: 200;
}
.page-header .logo {
  width: 100px;
  margin-right: 10px;
}
.page-header .view-source {
  font-weight: 200;
  font-size: 12px;
}
.page-header h2 {
  color: #fff;
  font-size: 18px;
  font-weight: normal;
}
</style>
  <script src="https://cdn.jsdelivr.net/npm/promise-polyfill@7/dist/polyfill.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropbox.js/10.27.0/Dropbox-sdk.min.js" integrity="sha512-nTLJySi/DUYzRvvxWOxf31QS5191sN1gpoq6EqGFHPFH0RlM6xOiY6jEp9dmwhDlyFmCmicwLOMnE+fUmo02KQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
  <!-- Example layout boilerplate -->
  <header class="page-header">
    <div class="container">
      <nav>
        <a href="/">
          <h1>
            <img src="https://cfl.dropboxstatic.com/static/images/brand/logotype_white-vflRG5Zd8.svg" class="logo" />
            JavaScript SDK Examples
          </h1>
        </a>
        <a href="https://github.com/dropbox/dropbox-sdk-js/tree/main/examples/javascript" class="view-source">View Source</a>
      </nav>
      <h2 class="code">
        <a href="/">examples</a> / basic
      </h2>
    </div>
  </header>

  <!-- Example description and UI -->
  <section class="container main">
    <p>This example fetches the contents of your root Dropbox directory. It uses the <code>Dropbox.filesListFolder()</code> method [<a href="http://dropbox.github.io/dropbox-sdk-js/Dropbox.html#filesListFolder">docs</a>].</p>

    <form id="basic-form" onSubmit="return listFiles()">
      <input type="text" id="access-token" placeholder="Access token" />
      <button type="submit">Submit</button>
    </form>

    <!-- The files returned from the SDK will be added here -->
    <ul id="files"></ul>

    <p class="info">To obtain an access token for quick testing, you can go to <a href="https://dropbox.github.io/dropbox-api-v2-explorer/#files_list_folder" target="_blank">API Explorer</a> click the "Get Token" button on the top right, copy the token it creates and then paste it here.</p>
  </section>

  <!-- Scripts to run example -->
  <script>
    var form = document.getElementById('basic-form');

    form.onsubmit = function listFiles(e) {
      e.preventDefault();

      var ACCESS_TOKEN = document.getElementById('access-token').value;
      var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
      dbx.filesListFolder({path: ''})
        .then(function(response) {
          console.log('response', response)
          displayFiles(response.result.entries);
        })
        .catch(function(error) {
          console.error(error);
        });
    }

    function displayFiles(files) {
      var filesList = document.getElementById('files');
      var li;
      for (var i = 0; i < files.length; i++) {
        li = document.createElement('li');
        li.appendChild(document.createTextNode(files[i][".tag"] + " " +  files[i].name));
        filesList.appendChild(li);
      }
    }
  </script>
</body>
</html>

EN

回答 1

Stack Overflow用户

发布于 2022-04-09 13:45:43

快速尝试,未经测试的代码,但您可以使用它作为灵感:

代码语言:javascript
复制
form.onsubmit = function listFiles(e) {
    e.preventDefault();

    var ACCESS_TOKEN = document.getElementById('access-token').value;
    var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
    var entries = {};
    let fetch_files = function(_path, entries){
        await dbx.filesListFolder({path: _path})
        .then(function(response) {
            console.log('response', response);
            entries = response.result.entries;
            for (var i = 0; i < entries.length; i++) {
                if(entries[i]['.tag'] == 'folder'){
                    entries[i]['subentries'] = {};
                    fetch_files(entries[i]['path_display'], entries[i]['subentries']);
                }
            }
        })
        .catch(function(error) {
            console.error(error);
        });
    };
    fetch_files('', entries);
    if(Object.keys(entries).length !== 0){
        displayFiles(entries);
    }
}

function displayFiles(files) {
    var filesList = document.getElementById('files');
    let append_list = function(arr, recursion){
        var li;
        for (var i = 0; i < arr.length; i++) {
            li = document.createElement('li');
            li.appendChild(document.createTextNode("&nbsp;".repeat(recursion * 4) + arr[i][".tag"] + " " +  arr[i].name));
            filesList.appendChild(li);
            if('subentries' in arr[i]){
                append_list(arr[i]['subentries'], recursion + 1);
            }
        }
    }
    append_list(files, 0)
}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71808331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档