PHP: 操作 Dropbox, 查看,下载,上传,删除等, dropbox php client

PHP: 操作 Dropbox, 查看,下载,上传,删除等, dropbox php client
PHP: 操作 Dropbox, 查看,下载,上传,删除等, dropbox php client

 

项目地址:https://kunalvarma05.github.io/dropbo…

 

入门

要开始使用Dropbox API,您需要一个应用程序。您可以在此处为Dropbox API创建新的应用:https://www.dropbox.com/developers/apps

更多Dropbox API创建详情,请参考:Linux: 命令行访问 Dropbox, 命令行查看或上传文件到 Dropbox, 命令行调用Dropbox V2 API

 

系统要求

 

安装

Dropbox PHP SDK可以通过Composer安装。

$ php composer require kunalvarma05/dropbox-php-sdk

 

配置

首先,需要使用从Dropbox Developer App Dashboard获得的client_idclient_secret配置DropboxApp类,方法是创建一个Application。

use Kunnu\Dropbox\DropboxApp;

$app = new DropboxApp("client_id", "client_secret");

 

如果您已有访问令牌,则可以将其作为第三个参数传递给上面的构造函数。

$app = new DropboxApp("client_id", "client_secret", 'access_token');

Dropbox服务类需要与Dropbox的API来工作。要配置Dropbox服务类,需要将上面创建的DropboxApp的实例作为第一个参数传递。

use Kunnu\Dropbox\Dropbox;

$dropbox = new Dropbox($app);

 

快速开始

用法很简单。在Dropbox的与Dropbox的API交互所需的服务类房屋的所有方法(其中大部分,现在)。

use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxApp;

//Configure Dropbox Application
$app = new DropboxApp("client_id", "client_secret", "access_token");

//Configure Dropbox service
$dropbox = new Dropbox($app);

//Get File Metadata
$fileMetadata = $dropbox->getMetadata("/helloworld.txt");

//File Name
$fileMetadata->getName();

 

详细使用指南

 

身份验证和授权

大多数情况下,对Dropbox API提出的所有请求都需要访问令牌。我们可以使用DropboxAuthHelper类获取用户访问令牌。

以下是身份验证和授权流程的工作原理:

  1. 使用DropboxAuthHelper生成带有该getAuthUrl()方法的登录/授权URL 。
  2. 该URL将用户带到应用程序授权屏幕以进行访问批准。用户批准/授予对您应用的访问权限后:A.如果a redirect_uri作为参数传递给getAuthUrl()方法,您将使用。重定向回预先指定的URL(redirect_uriauthorization codeB.如果redirect_uri未提供a,authorization code将直接呈现给用户。
  3. 我们可以通过该getAccessToken()方法获取用户访问令牌,方法是传递authorization code上一步中获得的(CSRF state如果redirect_uri指定了一个令牌,则获取令牌)。

例:

header.php

<?php
session_start();

require_once 'vendor/autoload.php';

use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxApp;

//Configure Dropbox Application
$app = new DropboxApp("client_id", "client_secret");

//Configure Dropbox service
$dropbox = new Dropbox($app);

//DropboxAuthHelper
$authHelper = $dropbox->getAuthHelper();

//Callback URL
$callbackUrl = "https://{my-website}/login-callback.php";
?>

 

login.php

<?php
require_once 'header.php';

//Fetch the Authorization/Login URL
$authUrl = $authHelper->getAuthUrl($callbackUrl);

echo "<a href='" . $authUrl . "'>Log in with Dropbox</a>";
?>

DropboxAuthHelper利用PHP会话存储CSRF令牌,该令牌将使用验证state参数返回与回调URL查询参数。在调用getAuthUrl()方法之前,请确保已启用会话。

 

让我们使用和获取的AccessToken以及回调URL作为查询参数。codestate

login-callback.php

<?php
require_once 'header.php'

if (isset($_GET['code']) && isset($_GET['state'])) {    
    //Bad practice! No input sanitization!
    $code = $_GET['code'];
    $state = $_GET['state'];

    //Fetch the AccessToken
    $accessToken = $authHelper->getAccessToken($code, $state, $callbackUrl);

    echo $accessToken->getToken();
}
?>

 

如果redirect_uri在调用时没有提供a getAuthUrl()(Authentication Flow步骤2B):

<?php
require_once 'header.php'

$code = 'code-presented-directly-to-the-user';

//Fetch the AccessToken
$accessToken = $authHelper->getAccessToken($code);

echo $accessToken->getToken();
?>

要撤消访问令牌,只需调用该revokeAccessToken()方法即可。

注意:在调用revokeAccessToken方法之前,必须已设置访问令牌。

$authHelper->revokeAccessToken();

 

使用文件

一旦实例化了Dropbox服务并获得了访问令牌,就可以轻松访问所有文件操作

 

获取文件/文件夹元数据

$file = $dropbox->getMetadata("/hello-world.txt");

或者

$file = $dropbox->getMetadata("/hello-world.txt", ["include_media_info" => true, "include_deleted" => true]);

获取文件详细信息:

//Id
$file->getId();

//Name
$file->getName();

//Size
$file->getSize();

getMetadata()方法将返回FileMetadata模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-get_metadata

 

列出文件夹内容

$listFolderContents = $dropbox->listFolder("/");

//Fetch Items
$items = $listFolderContents->getItems();

//Fetch Cusrsor for listFolderContinue()
$cursor = $listFolderContents->getCursor();

//If more items are available
$hasMoreItems = $listFolderContents->hasMoreItems();

 

listFolder()方法将返回MetadataCollection模型的实例。

$listFolderContents = $dropbox->listFolder("/");

//Fetch Items (Returns an instance of ModelCollection)
$items = $listFolderContents->getItems();

//All Items
$items->all();

//First Item
$items->first();

//Last Item
$items->last();

 

进一步调用模型的getItems()方法MetadataCollection,将返回模型的实例ModelCollection,这扩展了令人敬畏的Collection类。看看它的可用方法

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-list_folder

列表文件夹继续

使用从listFolder或listFolderContinue中检索到的光标,遍历所有文件并检索文件夹的更新。

$listFolderContents = $dropbox->listFolder("/");

//Process listFolder Items
...

//If more items are available
if ($listFolderContents->hasMoreItems()) {
    //Fetch Cusrsor for listFolderContinue()
    $cursor = $listFolderContents->getCursor();

    //Paginate through the remaining items
    $listFolderContinue = $dropbox->listFolderContinue($cursor);

    $remainingItems = $listFolderContinue->getItems();
}

listFolderContinue()方法将返回MetadataCollection模型的实例,与listFolder方法相同。

 

列出文件夹最新光标

//Fetch the latest cursor
$cursor = $dropbox-listFolderLatestCursor("/Public");

//Use this cursor to check if any files/folders where modified
//post this cursor was obtained
$modifiedItems = $dropbox->listFolderContinue($cursor)->getItems();

 

listFolderLatestCursor()方法将返回一个cursor

将此方法cursor与此listFolderContinue()方法一起使用将返回MetadataCollection模型的实例,其中包含自方法cursor获取以来已修改的文件/文件夹listFolderLatestCursor

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-list_folder-get_latest_cursor

 

列表修订

获取文件的修订版

$revisions = $dropbox->listRevisions("/hello-world.txt", ["limit" => 3]);

//All Revisions
$revisions->all();

//First Revision
$revisions->first();

//Last Revision
$revisions->last();

listRevisions()方法将返回ModelCollection模型的实例,该实例扩展了令人敬畏的Collection类。看看它的可用方法

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-list_revisions

 

搜索

在文件夹中搜索文件/文件夹。

$searchQuery = "hello world";
$searchResults = $dropbox->search("/", $searchQuery, ['start' => 0, 'max_results' => 5]);

//Fetch Items
$items = $searchResults->getItems();

//Fetch Cusrsor for calling search() with the `start` parameter/option for pagination
$startCursor = $searchResults->getCursor();

//If more items are available
if ($searchResults->hasMoreItems()) {
    //Pagination
    $moreSearchResults = $dropbox->search("/", $searchQuery, ['start' => $startCursor, 'max_results' => 5]);
}

search()方法将返回SearchResults模型的实例,该实例扩展了MetadataCollection模型。

$searchQuery = "hello world";
$searchResults = $dropbox->search("/", $searchQuery, ['start' => 0, 'max_results' => 5]);

//Fetch Items (Returns an instance of ModelCollection)
$items = $searchResults->getItems();

//All Items
$items->all();

//First Item (Returns an instance of SearchResult)
$item = $items->first();

//Get the type of match, that was found for the result
$item->getMatchType();

//Get the Metadata of the File or Folder
$item->getMetadata();

进一步调用模型的getItems()方法SearchResults,将返回模型的实例ModelCollection,其中每个项目将是SearchResult模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-search

 

创建文件夹

在给定路径创建一个文件夹

$folder = $dropbox->createFolder("/My Folder");

//Name
$folder->getName();

createFolder()方法将返回FolderMetadata模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-create_folder

 

删除文件/文件夹

删除给定路径中的文件或文件夹

$deletedFolder = $dropbox->delete("/My Folder");

//Name
$deletedFolder->getName();

delete()方法将返回DeletedMetadata模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-delete

 

恢复文件

将文件还原到特定版本

$revision = "rev:a1c10ce0dd78";
$restoredFile = $dropbox->restore("/Hello-World.txt", $rev);

//Name
$restoredFile->getName();

restore()方法将返回的任一实例FileMetadataFolderMetadataDeletedMetadata模型。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-restore

 

移动文件/文件夹

将文件或文件夹移动到其他位置

$file = $dropbox->move("/Private/Hello-World.txt", "/Public/Hello-World.txt");

//Name
$file->getName();

move()方法将返回的任一实例FileMetadataFolderMetadataDeletedMetadata模型。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-move

 

复制文件/文件夹

将文件或文件夹复制到其他位置

$file = $dropbox->copy("/Private/Hello-World.txt", "/Public/Hello-World.txt");

//Name
$file->getName();

copy()方法将返回的任一实例FileMetadataFolderMetadataDeletedMetadata模型。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-copy

 

获取复制参考

获取文件或文件夹的副本引用。此引用字符串可用于将该文件或文件夹传递给另一个用户的Dropbox saveCopyReference()

$copyReference = $dropbox->getCopyReference("/Hello-World.txt");

//Get Reference
$copyReference->getReference();

getCopyReference()方法将返回CopyReference模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-get

 

保存复制参考

将返回的副本引用保存getCopyReference到用户的Dropbox。

$copyReference = $dropbox->getCopyReference("/Hello-World.txt");

//Get Reference
$reference = $copyReference->getReference();

//Save Copy Reference
$file = $dropbox->saveCopyReference("/My-Hello-World.txt", $reference);

//Name
$file->getName();

saveCopyReference()方法将返回其中一个FileMetadataFolderMetadata模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-save

 

获取临时链接

获取流式传输文件内容的临时链接。

$temporaryLink = $dropbox->getTemporaryLink("/my-logo.png");

//Get File Metadata
$file = $temporaryLink->getMetadata();

//Get Link
$temporaryLink->getLink();

getTemporaryLink()方法将返回TemporaryLink模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link

 

获取缩略图

获取图像文件的缩略图。

//Available sizes: 'thumb', 'small', 'medium', 'large', 'huge'
$size = 'small'; //Default size

//Available formats: 'jpeg', 'png'
$format = 'jpeg'; //Default format

$file = $dropbox->getThumbnail('/my-logo.jpg', $size, $format);

//Get File Contents
$contents = $file->getContents();

//Save File Contents to Disk
file_put_contents(__DIR__ . "/my-logo.jpg", $contents);

//Get File Metadata
$file->getMetadata();

getThumbnail()方法将返回Thumbnail模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail

 

上传和下载文件

使用此SDK轻松上传文件。

 

Dropbox文件

DropboxFile类表示要上传的文件。在将文件上载到Dropbox之前,您需要实例化一个DropboxFile类。传递DropboxFile类实例并不是强制性的,因为您可以将路径传递给文件。

按文件路径创建DropboxFile

一个DropboxFile实例可以通过传递路径到本地文件作为第一个参数和创建任选使所述接入模式(读或写)作为第二个参数,以构造。该createByPath()静态方法也可以用于相同的。

use Kunnu\Dropbox\DropboxFile;

$pathToLocalFile = __DIR__ . "/Hello-World.txt";

$dropboxFile = new DropboxFile($pathToLocalFile);

// OR

$mode = DropboxFile::MODE_READ;
$dropboxFile = new DropboxFile($pathToLocalFile, $mode);

// OR
// Note: The `$mode` parameter is mandatory for this method.
$dropboxFile = DropboxFile::createByPath($pathToLocalFile, $mode);

 

按文件流创建DropboxFile

一个DropboxFile实例还可以通过使用文件流创建。

use Kunnu\Dropbox\DropboxFile;

$pathToLocalFile = __DIR__ . "/Hello-World.txt";

// Automatically create stream through file path
$dropboxFile = DropboxFile::createByStream("/Hello-World.txt", $pathToLocalFile);

// OR

// Create stream through file stream
$fileStream = fopen($pathToLocalFile, DropboxFile::MODE_READ);
$dropboxFile = DropboxFile::createByStream("/Hello-World.txt", $fileStream);

 

自动文件上传

将文件自动上传到Dropbox,可以是单个请求,也可以是块。这是上传文件的推荐方法。

$file = $dropbox->upload($dropboxFile, "/My-Hello-World.txt", ['autorename' => true]);

//Uploaded File
$file->getName();

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-upload

 

简单文件上传

在单个请求中将文件上传到Dropbox。

$file = $dropbox->simpleUpload($dropboxFile, "/My-Hello-World.txt", ['autorename' => true]);

//Uploaded File
$file->getName();

simpleUpload()方法将返回FileMetadata上传文件的内容。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-upload

 

分块文件上传

将文件以块的形式上传到Dropbox。

//File size (bytes)
$fileSize = 400000000;

//Chunk Size
$chunkSize = $filSize / 4;

$file = $dropbox->uploadChunked($dropboxFile, "/game-of-thrones-fan-trailer.mp4", $filesize, $chunkSize, ['autorename' => true]);

//Uploaded File
$file->getName();

uploadChunked()方法将返回FileMetadata上传文件的内容。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-upload

 

按URL上传文件

保存网址

将指定的URL保存到用户Dropbox中的文件中。

$asyncJobID = $dropbox->saveUrl("/my-logo.png", 'http://mywebsite.com/wp-content/uploads/2016/06/logo.png');

saveUrl()方法将返回asyncJobID(异步作业ID)。该asyncJobID字符串是一个id,可用于使用该checkJobStatus方法获取异步作业的状态。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-list_folder-save_url

 

检查工作状态

检查saveUrl作业的状态。

$asyncJobID = $dropbox->saveUrl("/my-logo.png", 'http://mywebsite.com/wp-content/uploads/2016/06/logo.png');

//Check Status
$status = $dropbox->checkJobStatus($asyncJobID);

//Job Successful. File saved.
if ($status instanceof FileMetadata) {
    $file = $status;
    echo $file->getName();
} elseif ($status === "in_progress") {
    echo "Processing job...";
} elseif ($status === "failed") {
    echo "Job Failed!";
} else {
    echo $status;
}

checkJobStatus()方法将FileMetadata在成功或作业时返回保存的文件,该文件status可以是in_progressfailed

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-list_folder-save_url-check_job_status

 

下载文件

下载文件。

$file = $dropbox->download("/my-logo.png");

//File Contents
$contents = $file->getContents();

//Save file contents to disk
file_put_contents(__DIR__ . "/logo.png", $contents);

//Downloaded File Metadata
$metadata = $file->getMetadata();

//Name
$metadata->getName();

 

直接下载到文件

建议使用此方法,尤其是在下载大文件时。

// Download and the save the file at the given path
$file = $dropbox->download("/my-large-file.mp4", '/path-to-save-file-to.mp4');

//Downloaded File Metadata
$metadata = $file->getMetadata();

//Name
$metadata->getName();

download()方法将返回File模型。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#files-download

 

使用用户帐户

获取帐户信息,批量帐户信息和帐户空间使用情况。

获取当前帐户

获取当前授权用户的帐户。

$account = $dropbox->getCurrentAccount();

//Id
$account->getAccountId();

//Name
$account->getDisplayName();

//Email
$account->getEmail();

//Profile Pic URL
$account->getProfilePhotoUrl();

//Account Type
$account->getAccountType();

getCurrentAccount()方法将返回Account模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#users-get_current_account

 

获取帐户

获取用户的帐户。

$accountId = "dbid:AAH4f99T0taONIb-OurWxbNQ6ywGRopQngc";
$account = $dropbox->getAccount($accountId);

//Id
$account->getAccountId();

//Name
$account->getDisplayName();

//Email
$account->getEmail();

//Profile Pic URL
$account->getProfilePhotoUrl();

//Account Type
$account->getAccountType();

getAccount()方法将返回Account模型的实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#users-get_account

 

获取批量帐户

获取多个帐户。

$accountIds = [
"dbid:AAH4f99T0taONIb-OurWxbNQ6ywGRopQngc",
"dbid:AADRW_KJHkjHihoi8iujbJ78nmbB8jbKB98",
"dbid:AAH7e48H2kapNKb-OaONIbNQRop6ywGQngc",
];

$accounts = $dropbox->getAccounts($accountIds);

//All Accounts
$accounts->all();

//First Account
$account = $accounts->first();

//Name
$account->getDisplayName();

getAccounts()方法将返回AccountList扩展ModelCollection模型的模型实例。

有关详细信息和可用选项,请参阅:https//www.dropbox.com/developers/documentation/http/documentation#users-get_account_batch

 

获得空间使用

获取当前用户帐户的空间使用情况

$accountSpace = $dropbox->getSpaceUsage();

//Space Used
$used = $accountSpace['used'];

//Space Allocated
$allocated = $accountSpace['allocated'];

getSpaceUsage()方法将返回一个包含帐户空间使用详细信息的数组。这是一个示例响应:

{
    "used": 314159265,
    "allocation": {
        ".tag": "individual",
        "allocated": 10000000000
    }
}

 

使用共享链接和共享文件夹

创建和管理共享链接和共享文件夹。

 

目前,SDK没有与共享端点交互的专用方法,类似于获取文件/文件夹元数据上传文件的专用方法。

 

但是,SDK仍然可以向共享端点(或任何Dropbox API端点)发出请求并获取/解码数据。

例如,您可以创建如下共享链接:

/**
* Assuming you have configured the DropboxApp class
* @see https://github.com/kunalvarma05/dropbox-php-sdk/wiki/Configuration
*/
$dropbox = new Dropbox($app);
$pathToFile = "/hello-world.txt";

$response = $dropbox->postToAPI("/sharing/create_shared_link_with_settings", [
    "path" => $pathToFile
]);

$data = $response->getDecodedBody();

var_dump($data);

 

 

本文: PHP: 操作 Dropbox, 查看,下载,上传,删除等

Loading

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.