Após o upload de um objeto, o Object Storage Service (OSS) envia um callback ao servidor de aplicativos. Para configurar callbacks de upload, adicione os parâmetros necessários à solicitação de upload enviada ao OSS. Este tópico descreve como configurar callbacks de upload para upload simples e upload multipart.
Observações de uso
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Criar um OssClient.
Configure callbacks de upload para tarefas de upload simples
O código de exemplo a seguir mostra como configurar um callback de upload para uma tarefa de upload simples:
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
$object = "exampledir/exampleobject.txt";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Configure a callback when you upload the object.
// callbackUrl specifies the address of the callback server that receives the callback request. Example: https://oss-demo.aliyuncs.com:23450.
// (Optional) Set callbackHost to the value of the Host field included in the callback request header.
$url =
'{
"callbackUrl":"yourCallbackServerUrl",
"callbackHost":"yourCallbackServerHost",
"callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}",
"callbackBodyType":"application/x-www-form-urlencoded"
}';
// Specify custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:.
$var =
'{
"x:var1":"value1",
"x:var2":"value2"
}';
$options = array(OssClient::OSS_CALLBACK => $url,
OssClient::OSS_CALLBACK_VAR => $var
);
$result = $ossClient->putObject($bucket, $object, file_get_contents(__FILE__), $options);
print_r($result['body']);
print_r($result['info']['http_code']);
Configure callbacks de upload para tarefas de upload multipart
O código de exemplo a seguir mostra como configurar um callback de upload para uma tarefa de upload multipart:
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Core\OssUtil;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs.
$uploadFile = "D:\\localpath\\examplefile.txt";
/**
* Step 1: Initiate a multipart upload task and obtain the upload ID.
*/
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// An upload ID is returned. The ID is the unique identifier of a multipart upload task. You can initiate operations, such as canceling or querying a multipart upload task, based on the upload ID.
$uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n");
/*
* Step 2: Upload parts.
*/
$partSize = 10 * 1024 * 1024;
$uploadFileSize = sprintf('%u',filesize($uploadFile));
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
$fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
$toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
$upOptions = array(
$ossClient::OSS_FILE_UPLOAD => $uploadFile,
$ossClient::OSS_PART_NUM => ($i + 1),
$ossClient::OSS_SEEK_TO => $fromPos,
$ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
$ossClient::OSS_CHECK_MD5 => $isCheckMd5,
);
// Perform MD5 verification.
if ($isCheckMd5) {
$contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
$upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
}
try {
// Upload the parts.
$responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
} catch(OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n");
}
// $uploadParts is an array that consists of the ETag and part number of each part.
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
$uploadParts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $eTag,
);
}
/**
* Step 3: Complete the multipart upload task.
*/
// callbackUrl specifies the address of the callback server that receives the callback request. Example: http://oss-demo.aliyuncs.com:23450 or http://127.0.0.1:9090.
// (Optional) Set callbackHost to the value of the Host field included in the callback request header.
$json =
'{
"callbackUrl":"<yourCallbackServerUrl>",
"callbackHost":"<yourCallbackServerHost>",
"callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}",
"callbackBodyType":"application/json"
}';
// Specify custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:.
$var =
'{
"x:var1":"value1",
"x:var2":"value2"
}';
$options = array(OssClient::OSS_CALLBACK => $json,
OssClient::OSS_CALLBACK_VAR => $var);
// Provide all valid $uploadParts when you perform this operation. After OSS receives the $uploadParts, OSS verifies all parts one by one. After all parts are verified, OSS combines the parts into a complete object.
$ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts, $options);
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");