uploadcare / uploadcare-php
Uploadcare PHP 集成通过封装上传和 REST API 来处理文件的上传和后续操作。
Requires
- php: >=7.4 || >=8.0
- ext-curl: *
- ext-json: *
- guzzlehttp/guzzle: ^7.5
- guzzlehttp/psr7: ^2.4
- symfony/polyfill-php80: ^1.26
- symfony/polyfill-uuid: ^1.26
Requires (Dev)
- fakerphp/faker: ^1.20
- friendsofphp/php-cs-fixer: ^3.11
- phpunit/phpunit: ^9.5
- symfony/dotenv: ^5.4
- symfony/var-dumper: ^5.4
- vimeo/psalm: ^4.27
- dev-master
- v4.2.0
- v4.1.1
- v4.1.0
- v4.0.2
- v4.0.1
- v4.0.0
- v3.2.4
- v3.2.3
- v3.2.2
- v3.2.1
- v3.2
- v3.1.1
- v3.0.3
- v3.0.2
- 3.0.1
- 3.0.0
- v2.4.1-rc
- 2.4.0-rc
- v2.3.0
- v2.2.1
- v2.2.0
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.0
- v2.0.0-rc1
- v1.5.5
- v1.5.4
- v1.5.3
- v1.5.2
- v1.5.1
- v1.5.0
- v1.4.1
- v1.4.0
- v1.3.3
- v1.3.2
- v1.3.1
- v1.3.0
- v1.2.6
- v1.2.5
- v1.2.4
- v1.2.3
- v1.2.2
- v1.2.1
- 1.1.3
- v1.1.1
- 1.0.9
- v1.0.8
- v1.0.7
- v1.0.5
- v1.0.4
- 1.0.3
- dev-develop
- dev-release-2.0
This package is auto-updated.
Last update: 2024-09-09 22:43:48 UTC
README
Uploadcare PHP 集成通过封装上传和 REST API 来处理文件的上传和后续操作。
需求
php7.4+
或php8.0+
php-curl
php-json
安装
在安装 uploadcare-php
之前,获取 PHP 依赖管理器 Composer,因为它将简化安装过程。
步骤 1 — 更新你的 composer.json
"require": { "uploadcare/uploadcare-php": "^4.0" }
步骤 2 — 运行 Composer
php composer.phar update
或者,你可以运行 composer.phar require uploadcare/uploadcare-php
,而不是步骤 1 和 2。
步骤 3 — 以你喜欢的任何方式(例如,使用 $_ENV
变量)定义你的 Uploadcare 公共和秘密 API 密钥
将 API 密钥添加到你的配置对象中。例如
# config.php $_ENV['UPLOADCARE_PUBLIC_KEY'] = '<your public key>'; $_ENV['UPLOADCARE_SECRET_KEY'] = '<your secret key>';
步骤 4 — 包含标准的 Composer 自动加载文件
require_once 'vendor/autoload.php';
步骤 5 — 创建一个 Uploadcare\Configuration
类的对象
$configuration = Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']);
所有后续操作都将使用此配置对象。
配置对象
有几种方法可以创建一个有效的配置对象。我们建议使用类的静态方法
$configuration = \Uploadcare\Configuration::create('<your public key>', '<your secret key>');
或者,你可以显式地创建一个安全签名、HTTP 客户端和序列化类。然后创建一个配置
$sign = new \Uploadcare\Security\Signature('<your secret key>', 3600); // Must be an instance of \Uploadcare\Interfaces\SignatureInterface $client = \Uploadcare\Client\ClientFactory::createClient(); // Must be an instance of \GuzzleHttp\ClientInterface $serializer = new \Uploadcare\Serializer\Serializer(new \Uploadcare\Serializer\SnackCaseConverter()); // Must be an instance of \Uploadcare\Interfaces\Serializer\SerializerInterface $configuration = new \Uploadcare\Configuration('<your public key>', $sign, $client, $serializer);
如你所见,工厂方法是标准使用的更方便的方法。
使用
你可以在这个 Uploadcare 示例项目 中找到完整的示例。
首先,创建一个 API 对象
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $api = new \Uploadcare\Api($configuration);
上传文件
本节描述了将文件上传到 Uploadcare 的多种方法。
你可以使用核心 API 对象进行任何类型的上传
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $uploader = (new \Uploadcare\Api($configuration))->uploader();
首先,文件可以从 URL 上传。以下代码返回一个用于检查文件上传状态的令牌
$url = 'https://httpbin.org/image/jpeg'; $result = $uploader->fromUrl($url, 'image/jpeg'); // If success, $result will be string to check upload status (see below)
你可以同步地从 URL 上传文件
$url = 'https://httpbin.org/image/jpeg'; $result = $uploader->syncUploadFromUrl($url, 'image/jpeg'); // $result is Uploadcare\Interfaces\File\FileInfoInterface
检查上传中的文件状态
$url = 'https://httpbin.org/image/jpeg'; $result = $uploader->fromUrl($url, 'image/jpeg'); $status = $uploader->checkStatus($result); // Instance of Uploadcare\Interfaces\File\FileInfoInterface with isReady() === false until file is not uploaded.
上传文件的另一种方法是使用 路径
$path = __DIR__ . '/squirrel.jpg'; $result = $uploader->fromPath($path, 'image/jpeg'); // In success $result will contain uploaded Uploadcare\File class
当使用文件指针时也适用
$path = __DIR__ . '/squirrel.jpg'; $result = $uploader->fromResource(\fopen($path, 'rb'), 'image/jpeg');
还有一个从 文件内容 上传文件的选择。你还需要指定 MIME 类型
$path = __DIR__ . '/squirrel.jpg'; $result = $uploader->fromContent(\file_get_contents($path), 'image/jpeg');
安全签名。如果你使用安全上传,可以使用 getSignature
方法获取一个 SignatureInterface
实例。例如
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $uploader = (new \Uploadcare\Api($configuration))->uploader(); $signature = $uploader->getSignature(); $key = $signature->getSignature(); // Sign string $expired = $signature->getExpire()->getTimestamp(); // Time when secure signature will expire
文件元数据
每种上传方法都可以设置一个 文件元数据。例如
$path = __DIR__ . '/squirrel.jpg'; $result = $uploader->fromPath($path, 'image/jpeg', null, '1', ['type' => 'animal', 'kind' => 'squirrel']);
你将在 Uploadcare\File
响应的 metadata
对象中看到这些值。
分片上传
如果你有一个大文件(超过 100Mb / 10485760 字节),上传器将自动使用 分片上传 来处理它。这需要更长的时间来上传,并且我们不推荐在 Web 环境中使用它。
Uploadcare\File
类
此类实现了 Uploadcare\Interfaces\File\FileInfoInterface
并有额外的(除接口之外)方法
store()
— 将此文件存储到存储中。返回Uploadcare\File
对象。delete()
— 删除此文件。返回Uploadcare\File
对象。copyToLocalStorage($store = true)
— 将此文件复制到本地存储。copyToRemoteStorage($target, $makePublic = true, $pattern = null)
— 将此文件复制到远程存储。
所有这些操作都可以通过文件API访问,您也可以通过 Uploadcare\File
对象访问它们。
文件操作
对于任何文件操作类型,您需要创建一个带有配置对象的 Uploadcare\Api
实例,并调用 file()
方法。
$config = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $fileApi = (new \Uploadcare\Api($config))->file();
之后,您可以访问文件操作方法
listFiles($limit = 100, $orderBy = 'datetime_uploaded', $from = null, $addFields = [], $stored = null, $removed = false)
— 文件列表。返回一个Uploadcare\FileCollection
实例(见下文)。集合中的每个元素都是一个Uploadcare\File
。参数- int
$limit
单个响应中列表中文件的首选数量。默认为100,最大为1000。 - string
$orderBy
指定返回列表中文件的排序方式。 - string|int|null
$from
文件筛选的起点。该值取决于您的$orderBy
参数值。 - array
$addFields
已弃用 自v4.0.1起,此参数已弃用,将在v4.1中删除 - bool|null
$stored
true
只包含存储的文件,false
包含临时文件。如果没有设置(默认):将包含存储和未存储的文件。 - bool
$removed
true
仅包含响应中的已删除文件,false
包含现有文件。默认值为false。
- int
nextPage(FileListResponseInterface $response)
— 从上一条回答中获取下一页,如果存在下一页。您可以在简单的while
循环中使用它,例如$config = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $fileApi = new \Uploadcare\Apis\FileApi($config); $page = $fileApi->listFiles(5); // Here is a FileListResponseInterface while (($page = $fileApi->nextPage($page)) !== null) { $files = $page->getResults(); }
getPageRequestParameters(string | null $url)
— 获取一个包含下一页请求参数的数组。用于创建到列表的上一页/下一页的链接。storeFile(string $id)
— 通过UUID存储单个文件。返回Uploadcare\File
(FileInfoInterface
)。以文件UUID作为参数。deleteFile(string $id)
— 删除单个文件。返回文件信息。以文件UUID作为参数。fileInfo(string $id)
— 一旦您获取了文件列表,您可能想获取一些特定于文件的信息。返回FileInfoInterface
。以文件UUID数组作为参数。batchStoreFile(array $ids)
— 用于一步存储多个文件。每个请求支持最多100个文件。以文件UUID数组作为参数。batchDeleteFile(array $ids)
— 用于一步删除多个文件。以文件UUID数组作为参数。copyToLocalStorage(string $source, bool $store)
— 用于将原始文件或其修改版本复制到默认存储。参数$source
— 要复制的文件的CDN URL或UUID。$store
参数仅适用于Uploadcare存储。
copyToRemoteStorage(string $source, string $target, bool $makePublic = true, string $pattern = '${default}')
— 将原始文件或其修改版本复制到自定义存储。参数$source
— 要复制的文件的CDN URL或UUID。$target
— 定义与您的项目相关的自定义存储名称,这意味着您正在将文件复制到指定的自定义存储。请注意,您可以将多个存储与一个S3存储桶关联起来。$makePublic
—true
使复制的文件可通过公开链接访问,false
反转此行为。$pattern
— 该参数用于指定Uploadcare传递给自定义存储的文件名。如果省略该参数,我们将使用自定义存储的模式。使用任何允许的组合值。
有关详细信息,请参阅 API 文档。
Uploadcare\FileCollection
类
此类实现了 Uploadcare\Interfaces\File\CollectionInterface
,并且除了接口外还有额外的方法。
store()
— 将集合中的所有文件存储起来。底层调用FileApi::batchStoreFile()
。delete()
— 删除集合中的所有文件。
集合中的每个文件都是一个 Uploadcare\File
类的实例。
Uploadcare\File
类
此类实现了 FileInfoInterface
,并为文件操作提供了额外的方法。
store()
— 存储当前文件。delete()
— 删除当前文件。copyToLocalStorage($store = true)
— 将当前文件复制到默认存储。copyToRemoteStorage($target, $makePublic = true, $pattern = null)
— 将当前文件复制到自定义存储;
如您所见,额外的方法可以帮助您在不直接调用API的情况下调用API方法。
附加组件操作
Uploadcare提供了一些针对图像的额外操作。
对象识别
从库中调用对象识别
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $api = new \Uploadcare\Api($configuration); /** @var \Uploadcare\Interfaces\File\FileInfoInterface $file */ $file = $api->file()->listFiles()->getResults()->first(); # Request recognition, get token to check status $token = $api->addons()->requestAwsRecognition($file); while (($status = $api->addons()->checkAwsRecognition($token)) !== 'done') { \usleep(1000); if ($status === 'error') { throw new \Exception('Error in process'); } } $recognitionData = $api->file()->fileInfo($file->getUuid())->getAppdata()->getAwsRekognitionDetectLabels(); // Instance of \Uploadcare\Interfaces\File\AppData\AwsRecognitionLabelsInterface
不安全内容检测
从库中调用不安全内容检测
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $api = new \Uploadcare\Api($configuration); /** @var \Uploadcare\Interfaces\File\FileInfoInterface $file */ $file = $api->file()->listFiles()->getResults()->first(); # Request recognition, get token to check status $token = $api->addons()->requestAwsRecognitionModeration($file); while (($status = $api->addons()->checkAwsRecognitionModeration($token)) !== 'done') { \usleep(1000); if ($status === 'error') { throw new \Exception('Error in process'); } } $recognitionModerationData = $api->file()->fileInfo($file->getUuid())->getAppdata()->getAwsRekognitionDetectModerationLabels() // Instance of \Uploadcare\Interfaces\File\AppData\AwsModerationLabelInterface
移除背景
从图像中移除背景
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $api = new \Uploadcare\Api($configuration); /** @var \Uploadcare\Interfaces\File\FileInfoInterface $file */ $file = $api->file()->listFiles()->getResults()->first(); # Request recognition, get token to check status $token = $api->addons()->requestRemoveBackground($file); while (($status = $api->addons()->checkRemoveBackground($token)) !== 'done') { \usleep(1000); if ($status === 'error') { throw new \Exception('Error in process'); } } $removeBackgroundData = $api->file()->fileInfo($file->getUuid())->getAppdata()->getRemoveBg(); // Instance of \Uploadcare\Interfaces\File\AppData\RemoveBgInterface
病毒扫描
$configuration = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $api = new \Uploadcare\Api($configuration); /** @var \Uploadcare\Interfaces\File\FileInfoInterface $file */ $file = $api->file()->listFiles()->getResults()->first(); # Request antivirus scan and get token: $token = $api->addons()->requestAntivirusScan($file); while (($status = $api->addons()->checkAntivirusScan($token)) !== 'done') { \usleep(1000); if ($status === 'error') { throw new \Exception('Error in process'); } }
分组操作
对于任何类型的分组操作,您需要创建一个带有配置对象的 Uploadcare\Api
实例,并调用 group()
方法
$config = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $groupApi = (new \Uploadcare\Api($config))->group();
之后,您可以访问分组操作方法
createGroup($files)
— 创建文件组。您可以将ID数组或Uploadcare\File\FileCollection
作为参数传递。返回一个Uploadcare\File\Group
对象。listGroups($limit, $asc = true)
— 获取分页的组列表。默认限制为100,默认排序为创建日期和时间(升序)。您可以通过设置$asc = false
将排序顺序反转到降序日期。返回Uploadcare\Response\GroupListResponse
。groupInfo($id)
— 通过UUID获取文件组信息。返回一个Uploadcare\Group
对象。removeGroup($id): void
— 通过UUID或Uploadcare\Group
对象删除组。
Uploadcare\Group
类
此类实现了 Uploadcare\Interfaces\GroupInterface
。Uploadcare\Group
对象的 getFiles()
方法返回 FileCollection。
项目操作
像往常一样,项目API可以通过主API对象访问。
$config = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $projectApi = (new \Uploadcare\Api($config))->project();
您可以通过调用 getProjectInfo
方法获取项目信息
$projectInfo = $projectApi->getProjectInfo();
现在,$projectInfo
变量包含了以下方法的 Uploadcare\Interfaces\Response\ProjectInfoInterface
实现
getCollaborators()
— 存储合作者信息的数组。键是合作者电子邮件,值是合作者姓名。getName()
— 作为字符串的项目名称。getPubKey()
— 作为字符串的项目公钥。isAutostoreEnabled()
— 如果项目文件自动存储,则返回true
。
Webhooks
调用webhook API
$config = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $webhookApi = (new \Uploadcare\Api($config))->webhook();
方法如下
listWebhooks()
— 返回项目webhooks列表,作为Uploadcare\WebhookCollection
类的实例。此集合的每个元素都是一个Uploadcare\Webhook
类的实例(见下文);createWebhook(string $targetUrl, bool $isActive = true, string $signingSecret = null, string $event = 'file.uploaded')
— 为事件创建一个新的webhook。返回Uploadcare\Webhook
类。事件类型在 此处 描述updateWebhook($id, array $parameters)
— 使用这些参数更新现有的webhook。参数可以是target_url
— 目标回调URL;event
— 目前只支持file.uploaded
事件。is_active
— 返回webhook的活动状态。signing_secret
— Webhook签名密钥。请参阅安全Webhook
deleteWebhook
— 通过URL删除webhook。
Uploadcare\Webhook
类
此类实现了Uploadcare\Interfaces\Response\WebhookInterface
,并具有接口外的额外方法
delete()
— 删除webhook。底层调用Uploadcare\Interfaces\Api\WebhookApiInterface::deleteWebhook()
;updateUrl($url)
— 使用新的URL更新webhook(WebhookApiInterface::updateWebhook()
)。activate()
— 设置webhook为活动状态(WebhookApiInterface::updateWebhook()
)。deactivate()
— 设置webhook为非活动状态(WebhookApiInterface::updateWebhook()
)。
转换操作
您可以使用Conversion API将文档、图像和编码视频文件。
文档和图像转换
为后续转换请求创建新对象
$request = new \Uploadcare\Conversion\DocumentConversionRequest('pdf');
默认参数和示例如下
$targetFormat = 'pdf'
— 目标格式。$throwError = false
— 如果设置为true
,错误的请求将抛出异常,否则,它将返回null。$store = true
— 转换结果将发送到您的默认存储。$pageNumber = 1
— 指定在多页文档中要转换的页面。
然后,您可以将文件转换为
$config = \Uploadcare\Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']); $convertor = (new \Uploadcare\Api($config))->conversion(); $result = $convertor->convertDocument($file, $request);
结果将包含以下两种对象之一
- 成功操作时包含转换结果的
ConvertedItemInterface
对象,或 - 发生错误时(如果请求中的
$throwError
设置为false
),包含错误的ResponseProblemInterface
对象。
ConvertedItemInterface
将包含转换文档的UUID和带有转换作业ID的令牌。您可以使用此ID(或ConvertedItemInterface
对象本身)请求转换作业的状态。
您还可以将true
传递给请求对象的setSaveInGroup
方法。
$request = (new \Uploadcare\Conversion\DocumentConversionRequest('pdf'))->setSaveInGroup(true);
在这种情况下,文档转换的结果将存储在组中。有关详细信息,请参阅此处。
$status = $convertor->documentJobStatus($result); // or $result->getToken()
此状态对象将实现ConversionStatusInterface
,并具有以下方法
getStatus()
— 状态字符串。挂起、处理、完成、失败或取消。getError()
— 如果发生错误,则返回错误字符串或null。getResult()
—StatusResultInterface
对象。
您可以请求批量转换以处理多个文档
$result = $convertor->batchConvertDocuments($files, $request);
$files
可以是文件ID的数组/集合或FileInfo对象,结果将是BatchResponseInterface
的实现。
视频处理
如前一步获取转换API并执行VideoEncodingRequest
$request = new \Uploadcare\Conversion\VideoEncodingRequest();
您可以通过对象设置器设置此请求的各种参数
$request = (new \Uploadcare\Conversion\VideoEncodingRequest()) ->setHorizontalSize(1024) // Sets the horizontal size for result. ->setVerticalSize(768) // Sets the vertical size of result. ->setResizeMode('preserve_ratio') // Sets the resize mode. Mode can be one of 'preserve_ratio', 'change_ratio', 'scale_crop', 'add_padding' ->setQuality('normal') // Sets result quality. Can be one of 'normal', 'better', 'best', 'lighter', 'lightest' ->setTargetFormat('mp4') // Sets the target format. Can be one of 'webm', 'ogg', 'mp4'. Default 'mp4' ->setStartTime('0:0') // Sets the start time. Time string must be an `HHH:MM:SS.sss` or `MM:SS.sss` ->setEndTime('22:44') // Sets the end time. String format like start time string ->setThumbs(2) // Sets count of video thumbs. Default 1, max 50 ->setStore(true) // Tells store result at conversion ends. Default is true
如果您没有为转换请求设置任何选项,则默认值如下:mp4格式,全长和正常质量。
转换API的convertVideo
方法的结果将是ConversionResult
或ResponseProblemobject
。包含uuid
和token
的ConversionResult对象。您可以使用令牌通过videoJobStatus
方法请求视频转换作业的状态。
您还可以使用batchConvertVideo
方法请求批量视频转换。第一个参数必须是FileInfo或文件uuid的集合,第二个是VideoEncodingRequest
对象。
安全交付
您可以使用自己的自定义域和CDN提供商,通过认证URL发送文件(请参阅原始文档)。
要从库中生成认证URL,您应该这样做
- 按常规创建配置;
- 创建
Uploadcare\AuthUrl\AuthUrlConfig
对象。此对象将提供令牌、过期时间戳以及您的自定义域URL生成器。$token
在构造函数中必须是Uploadcare\AuthUrl\Token\TokenInterface
的一个实例; - 从
FileApi::generateSecureUrl($id)
或从Uploadcare\File::generateSecureUrl()
生成安全URL
例如
use Uploadcare\Configuration; use Uploadcare\AuthUrl\AuthUrlConfig; use Uploadcare\Api; use Uploadcare\AuthUrl\Token\AkamaiToken; $authUrlConfig = new AuthUrlConfig('mydomain.com', new AkamaiToken('secretKey', 300)); $config = Configuration::create($_ENV['UPLOADCARE_PUBLIC_KEY'], $_ENV['UPLOADCARE_SECRET_KEY']) ->setAuthUrlConfig($authUrlConfig); $api = new Api($config); $file = $api->file()->listFiles()->getResults()->first(); // Get secure url from file $secureUrl = $file->generateSecureUrl(); // you can use KeyCdnUrlGenerator or AkamaiUrlGenerator // Or from API instance $secureUrlFromApi = $api->file()->generateSecureUrl($file);
安全交付转换后的图片
您可以在应用了图像转换的安全URL上设置自定义ACL。只需将带有转换的图像UUID添加到 generateSecureUrl
方法中即可。
$api->file()->generateSecureUrl('/*/'); # Access to all files in project $api->file()->generateSecureUrl('/{uuid}/-/resize/640x/other/transformations/'); # Access to modified file version
测试
PHP 7.1+ 测试可以在 "tests" 目录中找到。所有测试都基于PHPUnit,因此您需要在运行测试之前安装它。
使用以下命令运行测试
`vendor/bin/phpunit --exclude-group local-only`
--exclude-group local-only
表示测试不会发送真实的API请求。如果您想运行所有测试,请创建 tests
目录中的 .env.local
文件,并放置以下变量,包含您真实的公共和秘密API密钥
# tests/.env.local UPLOADCARE_PUBLIC_KEY=<your public key> UPLOADCARE_secret_KEY=<your secret key>