O upload simples permite enviar conteúdo como string ou a partir de um arquivo local. Este tópico fornece exemplos de código para upload de string e de arquivo.
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 os endpoints compatíveis, consulte Regiões e endpoints.
Este tópico demonstra como criar 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.
Um objeto enviado por meio do upload simples não pode exceder 5 GB.
Permissões
Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não têm permissões por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.
|
API |
Ação |
Descrição |
|
PutObject |
|
Faz o upload de um objeto. |
|
|
Necessário se você especificar tags de objeto usando o cabeçalho |
|
|
|
Obrigatório quando o cabeçalho |
|
|
|
Fazer upload de uma string
O exemplo de código a seguir mostra como fazer o upload de uma string para o objeto exampledir/exampleobject.txt no bucket examplebucket.
<?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\Core\OssException;
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of your bucket's region. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the object. The path must not contain the bucket name. For example, exampledir/exampleobject.txt.
$object = "exampledir/exampleobject.txt";
// The string to upload.
$content = "Hello OSS";
// You can specify headers when you upload the string. For example, set the ACL to private or add custom metadata.
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-object-acl' => 'private',
'x-oss-meta-info' => 'yourinfo'
),
);
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->putObject($bucket, $object, $content, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
Fazer upload de um arquivo
O código de exemplo a seguir demonstra como enviar um arquivo local chamado examplefile.txt para o diretório exampledir do bucket examplebucket. Após o upload do arquivo local, o objeto no diretório exampledir recebe o nome exampleobject.txt.
<?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\Core\OssException;
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the object. The path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
$object = "exampledir/exampleobject.txt";
// Set the full path to the local file. For example, D:\\localpath\\examplefile.txt. If you omit the path, the file is uploaded from the project's root directory.
$filePath = "D:\\localpath\\examplefile.txt";
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->uploadFile($bucket, $object, $filePath);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");