O baixe condicional permite especifique uma ou mais condições ao baixar um objeto do Object Storage Service (OSS). O sistema baixa o objeto para a memória local ou para um arquivo local apenas se as condições definidas forem atendidas. Caso contrário, o sistema retorna um erro e não inicia o download.
Observações de uso
Este tópico utiliza 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 suportados, consulte Regiões e endpoints.
Este tópico demonstra como crie 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.
Para executar um download condicional, é necessária a permissão
oss:GetObject. Para mais informações, consulte Anexar uma política personalizada a um usuário RAM.
Condições
A tabela a seguir lista as condições suportadas pelo OSS. É possível usar If-Modified-Since e If-Unmodified-Since simultaneamente, bem como If-Match e If-None-Match.
|
Parâmetro |
Descrição |
Método |
|
If-Modified-Since |
Baixa o objeto caso ele tenha sido modificado após o horário especificado. Caso contrário, retorna um erro 304 Not modified. |
OssClient::OSS_IF_MODIFIED_SINCE |
|
If-Unmodified-Since |
Baixa o objeto se ele foi modificado exatamente no horário especificado ou antes dele. Caso contrário, retorna um erro 412 Precondition failed. |
OssClient::OSS_IF_UNMODIFIED_SINCE |
|
If-Match |
Baixa o objeto quando seu ETag corresponde ao ETag especificado. Caso contrário, retorna um erro 412 Precondition failed. Nota
Obtenha o ETag de um objeto usando o método $ossClient->getObjectMeta. |
OssClient::OSS_IF_MATCH |
|
If-None-Match |
Baixa o objeto se o ETag do objeto OSS for diferente do ETag especificado. Caso contrário, retorna um erro 304 Not modified. |
OssClient::OSS_IF_NONE_MATCH |
Baixe condicionalmente um objeto para a memória local
O código a seguir mostra como definir condições para baixar um objeto para a memória local:
<?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 set.
$provider = new EnvironmentVariableCredentialsProvider();
// The following example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.
$bucket= "yourBucketName";
// Specify the object name. The object name is the full path of the object that does not include the bucket name, such as exampledir/exampleobject.txt.
$object = "yourObjectName";
try{
$options = array(
OssClient::OSS_HEADERS => array(
// Download the object if it was modified after Fri, 9 Apr 2021 14:47:53 GMT.
OssClient::OSS_IF_MODIFIED_SINCE => "Fri, 9 Apr 2021 14:47:53 GMT",
// Download the object if it was modified at or before Wed, 13 Oct 2021 14:47:53 GMT.
OssClient::OSS_IF_UNMODIFIED_SINCE => "Fri, 13 Oct 2021 14:47:53 GMT",
// Download the object if its ETag does not match the specified ETag.
OssClient::OSS_IF_NONE_MATCH => '"5B3C1A2E0563E1B002CC607C****"',
// Download the object if its ETag matches the specified ETag.
OssClient::OSS_IF_MATCH => '"fba9dede5f27731c9771645a3986****"',
)
);
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Download the object to local memory.
$content = $ossClient->getObject($bucket, $object, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print ($content);
print(__FUNCTION__ . ": OK" . "\n");
Baixe condicionalmente um objeto para um arquivo local
O código a seguir mostra como definir condições para baixar um objeto para um arquivo local:
<?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 set.
$provider = new EnvironmentVariableCredentialsProvider();
// The following example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.
$bucket= "yourBucketName";
// Specify the object name. The object name is the full path of the object that does not include the bucket name, such as exampledir/exampleobject.txt.
$object = "yourObjectName";
// Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
$localfile = "yourLocalFile";
try{
$options = array(
OssClient::OSS_HEADERS => array(
// Download the object if it was modified after Fri, 9 Apr 2021 14:47:53 GMT.
OssClient::OSS_IF_MODIFIED_SINCE => "Fri, 9 Apr 2021 14:47:53 GMT",
// Download the object if it was modified at or before Wed, 13 Oct 2021 14:47:53 GMT.
OssClient::OSS_IF_UNMODIFIED_SINCE => "Fri, 13 Oct 2021 14:47:53 GMT",
// Download the object if its ETag does not match the specified ETag.
OssClient::OSS_IF_NONE_MATCH => '"5B3C1A2E0563E1B002CC607C****"',
// Download the object if its ETag matches the specified ETag.
OssClient::OSS_IF_MATCH => '"fba9dede5f27731c9771645a3986****"',
OssClient::OSS_FILE_DOWNLOAD => $localfile
)
);
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->getObject($bucket, $object, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}