dropbox

This article will teach you the bare minimum you need to know in order to start creating apps on top of the Dropbox API.

本文将教您一些基本知识,以便您开始在Dropbox API之上创建应用程序。

Once you’ve read it, you can also check out our free course on the Dropbox API if you’re interested in learning more. In that course, you’ll learn how to build an expense organizer app using modern JavaScript.

阅读后,如果您有兴趣了解更多信息,还可以查看有关Dropbox API的免费课程 。 在该课程中,您将学习如何使用现代JavaScript构建费用管理器应用。

This article uses JavaScript for its examples, however, the SDKs are very similar across languages, so even if you’re for example a Python developer, it should still be relevant.

本文使用JavaScript作为示例,但是,各语言之间的SDK非常相似,因此,即使您是Python开发人员,它也应具有相关性。

设置 (The setup)

In order to build on top of Dropbox, you first need a Dropbox account. After you’ve registered, head over to the developer section. Choose My apps on the lefthand side of the dashboard and click Create app.

为了在Dropbox之上构建,首先需要一个Dropbox 帐户 。 注册后,请转到开发人员部分。 在信息中心的左侧选择我的应用 ,然后点击创建应用

Choose the following settings, and give your app a unique name.

选择以下设置,并为您的应用指定唯一的名称。

Preferred settings for this tutorial

本教程的首选设置

In the dashboard, go to OAuth 2 section under Generated access token and click the Generate button to get an API accessToken, which we will save for later.

在仪表板中,转到“ 生成的访问令牌”下的OAuth 2部分,然后单击“ Generate按钮以获取API accessToken ,我们将保存该API供以后使用。

Now, let’s install the Dropbox desktop app. Log in to the app with your new developer credentials and you should be able to see a folder with the same name as your newly created app. In my case, it’s LearnDbxIn5Minutes.

现在,让我们安装Dropbox桌面应用程序 。 使用新的开发人员凭据登录到该应用程序,您应该能够看到一个与您新创建的应用程序名称相同的文件夹。 就我而言,它是LearnDbxIn5Minutes

Drop some files and images into the folder, so we can access them via our API.

将一些文件和图像拖放到该文件夹​​中,以便我们可以通过我们的API访问它们。

安装和初始Dropbox类 (Installation and initial Dropbox class)

Now let’s install Dropbox library to our project.

现在,将Dropbox库安装到我们的项目中。

npm install dropbox

npm install dropbox

要么 (or)

yarn add dropbox

yarn add dropbox

Import Dropbox and create dbx with our token and fetching library passed into our class instantiation. If you prefer axios or any other fetching library, feel free to pass it instead.

导入Dropbox并使用传递到我们的类实例化中的令牌和获取库创建dbx 。 如果您更喜欢axios或任何其他提取库,请随时传递它。

import { Dropbox } from 'dropbox';const accessToken = '<your-token-from-dashboard>';const dbx = new Dropbox({  accessToken,  fetch
});

Note that Dropbox is a named import. The reason is that there are other sub-libraries within 'dropbox', for example, DropboxTeam, but we will focus only on Dropbox in this tutorial.

请注意,Dropbox是命名的导入。 原因是'dropbox'中还有其他子库,例如DropboxTeam ,但是在本教程中,我们仅关注Dropbox

获取文件 (Getting files)

The first method we’re going to look at is for getting files.

我们要研究的第一种方法是获取文件。

dbx.filesListFolder({  path: ''
}).then(response => console.log(response))

filesListFolder() takes a path to the target folder and lists all the files inside. This method returns a promise.

filesListFolder()采用目标文件夹的路径,并列出其中的所有文件。 该方法返回一个promise。

Also, it’s worth keeping in mind that you’ll provide an empty string '' and not a slash'/' in order to get to the root of our app. Now the root is the root of our application folder  and not that of the Dropbox account. We can always change that option in the settings of our app.

另外,请记住,为了到达应用程序的根目录,您将提供一个空字符串''而不是斜杠'/' 。 现在,该根目录是我们的应用程序文件夹的根目录,而不是Dropbox帐户的根目录 。 我们随时可以在应用程序的设置中更改该选项。

When we run our code, the console should log the entries of our Dropbox folder:

当我们运行代码时,控制台应记录我们Dropbox文件夹的条目:

获取更多文件 (Getting more files)

In this part, we’re going to look at loading further files, with potential for implementing pagination or an infinite scroll feature.

在这一部分中,我们将研究加载更多文件,它们有可能实现分页或无限滚动功能。

For this purpose, Dropbox has got a concept of a cursor, which indicates our current position between the files that we’ve received and the ones that need to be sent.

为此,Dropbox有一个cursor概念,它指示我们在已接收文件和需要发送文件之间的当前位置。

For example, we have a folder with 10 files, and we requested 5. The cursor will let us know that there are more files to download via has-more: true property on the response. We can continue requesting files using filesListFolderContinue() passing in cursor until there are no more files left and we get has_more: false.

例如,我们有一个包含10个文件的文件夹,我们要求5。光标将告诉我们还有更多文件可以通过response上的has-more: true属性下载。 我们可以继续使用通过传入cursor filesListFolderContinue()来请求文件,直到没有剩余的文件并且得到has_more: false

const getFiles = async () => {  const response = await dbx.filesListFolder({  path: '',   limit: 5  })console.log(response)
}getFiles()

When we examine the response we got in the console we can see has_more: true.

当我们检查控制台中的响应时,可以看到has_more: true

Let’s update our code to handle cases when we’ve got more files to receive.

让我们更新代码以处理有更多文件要接收的情况。

const getFiles = async () => {  const response = await dbx.filesListFolder({  path: '',   limit: 5  })// We can perform a custom action with received files  processFiles(response.entries)if (response.has_more) {  // provide a callback for the newly received entries   // to be processed  getMoreFiles(response.cursor, more => processFiles(more.entries))  }
}getFiles()

We provide the cursor to let the API know the entries that we’ve received, so we won’t receive the same files again.

我们提供游标来让API知道我们已经收到的条目,因此我们不会再收到相同的文件。

const getMoreFiles = async (cursor, callback) => {  // request further files from where the previous call finished  const response = await dbx.filesListFolderContinue({ cursor })// if a callback is provided we call it  if (callback) callback(response)if (response.has_more) {  // if there are more files, call getMoreFiles recursively,  // providing the same callback.  await getMoreFiles(response.cursor, callback)  }
}

Note the callback we are providing to getMoreFiles() function. It’s a really neat trick to make sure that our newly received files get the same treatment as their predecessors.

请注意我们为getMoreFiles()函数提供的回调。 确保我们新收到的文件与以前的文件受到相同的对待,这是一个非常巧妙的技巧。

In the end, when there are no more files to get, we receive has_more: false

最后,当没有更多文件要获取时,我们收到has_more: false

It’s also worth mentioning that the recursive call is implemented here for simplicity of the tutorial, rather than for the performance of the function. If you have large amounts of data to load, please refactor this out into a more performant function.

还值得一提的是,此处递归调用的实现是为了简化本教程,而不是为了函数的性能。 如果要加载大量数据,请将其重构为性能更高的功能。

获取缩略图 (Getting thumbnails)

The third method we’re going to study is for getting thumbnails for our files.

我们将要研究的第三种方法是获取文件的缩略图。

In order to request thumbnails for the uploaded files, we can call filesGetThumbnailBatch().

为了请求上传文件的缩略图,我们可以调用filesGetThumbnailBatch()

dbx.filesGetThumbnailBatch({  entries: [{  path: '',  size: 'w32h32',  format: 'png',  }]
});

This endpoint is optimized for getting multiple thumbnails and it accepts an array of objects, where each object can have multiple properties specified.

该端点已针对获取多个缩略图进行了优化,它接受一个对象数组,其中每个对象可以指定多个属性。

The essential property is path, which holds the same caveats as in filesListFolder().

基本属性是path ,它具有与filesListFolder()相同的警告。

In our response, we can access our images via the thumbnail properties.

在响应中,我们可以通过thumbnail属性访问图像。

You can see that the thumbnails are not returned as links, but as really really long strings — this is a base64 image. You could use the string in your HTML to set src of <img> to "data:image/jpeg;base64, ${file.thumbnail}".

您可以看到缩略图不是作为链接返回的,而是真的很长的字符串-这是base64图像。 您可以使用HTML中的字符串将<img> src设置为"data:image/jpeg;base64, ${file.thumbnail}"

And if I render my response, I would get these amazing cats!

如果我做出回应,我会得到这些惊人的猫!

Image credits: Max Pixel (1, 2, 3)

图像学分:最大象素( 1 , 2 , 3 )

移动文件 (Moving files)

Lastly, we’re going to cover moving our files from one folder to another.

最后,我们将介绍将文件从一个文件夹移动到另一个文件夹的过程。

We can use filesMoveBatchV2() for moving our files in batches from one folder to another. This method works best when implemented as a part of an async function.

我们可以使用filesMoveBatchV2()将文件从一个文件夹批量移动到另一个文件夹。 当实现为async功能的一部分时,此方法最有效。

The method accepts entries array of objects, that consist of from_path and to_path properties.

该方法接受对象的entries数组,该对象数组包含from_pathto_path属性。

filesMoveBatchV2() returns either success if the call was immediately successful, in case there are only a few files to process. However, for bigger workloads, it’s going to return an object with a property async_job_id, and that means that your call is being executed and we will need to check up on it at a later stage.

如果仅要处理几个文件,则如果调用立即成功, filesMoveBatchV2()将返回任一success 。 但是,对于较大的工作负载,它将返回一个带有async_job_id属性的对象,这意味着您的调用正在执行,我们将在以后的阶段进行检查。

We can use filesMoveBatchCheckV2() to keep checking for completion of our job until it’s complete and is not in_progress any more.

我们可以使用filesMoveBatchCheckV2()来检查作业是否完成,直到完成并且不再是in_progress

const entries = {  from_path: 'origin_folder',  to_path: 'destination_folder
}const moveFiles = async () => {  let response = await dbx.filesMoveBatchV2({ entries })  const { async_job_id } = response  if (async_job_id) {  do {  response = await dbx.filesMoveBatchCheckV2({ async_job_id })  // This where we perform state update or any other action.  console.log(res)  } while (response['.tag'] === 'in_progress')  }
}

结语 (Wrap up)

Congratulations! You now have a very basic understanding of Dropbox API and its JavaScript SDK.

恭喜你! 您现在对Dropbox API及其JavaScript SDK有了非常基本的了解。

If you want to learn more about the Dropbox API and build an app on top of it with Vanilla JavaScript, be sure to check out our free course on Scrimba. It has, along with this post, been sponsored and paid for by Dropbox. This sponsorship helps Scrimba keep the lights on and it enables us to continue creating free content for our community throughout 2019. So a big thanks to Dropbox for that!

如果您想了解有关Dropbox API的更多信息并使用Vanilla JavaScript在其之上构建应用程序,请务必查看有关Scrimba的免费课程。 它和这篇文章都是由Dropbox赞助和支付的。 这项赞助有助于Scrimba保持亮灯状态,并使我们能够在整个2019年继续为社区创建免费内容。为此,非常感谢Dropbox!

Happy coding :)

快乐的编码:)

翻译自: https://www.freecodecamp.org/news/learn-the-dropbox-api-in-5-minutes-fd4626a0df18/

dropbox

dropbox_在5分钟内学习Dropbox API相关推荐

  1. 在五分钟内学习使用Python进行类型转换

    by PALAKOLLU SRI MANIKANTA 通过PALAKOLLU SRI MANIKANTA 在五分钟内学习使用Python进行类型转换 (Learn typecasting in Pyt ...

  2. html5 学习_5分钟内学习HTML

    html5 学习 by Eric Tirado 埃里克·蒂拉多(Eric Tirado) 5分钟内学习HTML (Learn HTML in 5 minutes) 快速教程可帮助您开始构建网站. (A ...

  3. js/d3.min.js_在5分钟内学习D3.js

    js/d3.min.js by Sohaib Nehal 通过Sohaib Nehal 在5分钟内学习D3.js (Learn D3.js in 5 minutes) 创建数据可视表示的简介 (An ...

  4. 网页视频15分钟自动暂停_在15分钟内学习网页爬取

    网页视频15分钟自动暂停 什么是网页抓取? (What is Web Scraping?) Web scraping, also known as web data extraction, is th ...

  5. react-hooks_在5分钟内学习React Hooks-初学者教程

    react-hooks Sometimes 5 minutes is all you've got. So in this article, we're just going to touch on ...

  6. 初学者css常见问题_5分钟内学习CSS Grid-初学者教程

    初学者css常见问题 Grid layouts are fundamental to the design of websites, and the CSS Grid module is the mo ...

  7. css flexbox模型_5分钟内学习CSS Flexbox-初学者教程

    css flexbox模型 快速介绍流行的布局模块 (A quick introduction to the popular layout module) In this post, you'll l ...

  8. 初学者css常见问题_5分钟内学习CSS-初学者教程

    初学者css常见问题 关于网络设计语言的快速教程. (A quick tutorial on the design language of the web.) CSS (Cascading Style ...

  9. react学习预备知识_在10分钟内学习React基础知识

    react学习预备知识 If you want to learn the basics of React in the time it takes you to drink a cup of coff ...

最新文章

  1. 在Ubuntu 12.04 64bit上搭建Crtmpserver视频直播服务
  2. Zookeeper集群部署和使用
  3. SQL server(MSSQL)客户端工具登录数据库的两种命令行登录方式
  4. [转载]Android创世纪 - 第二天
  5. css禁止双击dom节点被选中user-select:none
  6. leader选举的源码分析-startLeaderElection
  7. 201621123080《Java程序设计》第十一周学习总结
  8. 12c oracle 激活_Oracle 12C 安装教程
  9. T-SQL 常用日期格式
  10. explain分析SQL查询
  11. mysql+imx6+移植_imx6ulevk---MfgTool的使用心得
  12. ECS查询特权接口DescribeAccountAttributes发布
  13. linux vga 分辨率低,通过 VGA 接口连接显示器时分辨率不正确
  14. 【依赖高精度点云地图和三维激光雷达的定位方案】正态分布变换(NDT)定位及建图
  15. 公链、私链、联盟链、侧链简介
  16. 线性子空间的交、并、和、维数与直和等各种关系总结
  17. 最近做的智能垃圾桶程序代码(1)
  18. MFC 屏蔽ESC键和ENTER键关闭对话框的方法
  19. 同一局域网下多台电脑共享文件夹
  20. html中,table 的cellpadding cellspacing 属性失效

热门文章

  1. 【ICLR2019】Poster 论文汇总
  2. 【linux】 rm 防止误删
  3. 字节流抽象类 java
  4. 格式小结 css 0926
  5. charles-无法抓取https包的解决办法及效果
  6. temp191706考核点一,小结
  7. ubuntu中flashcache使用教程
  8. 深度访谈Amazon员工与HR:华裔因pip跳楼背后(图)
  9. js高级程序设计 - 温故而知新
  10. 【2018.05.04学习笔记】【linux基础知识10.1-10.5】