O upload simples permite enviar conteúdo como uma string ou a partir de um arquivo local. Este tópico fornece exemplos de código para upload de string e upload de arquivo.
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 compatíveis, consulte Regions and endpoints.
Este tópico demonstra a criação de uma instância OssClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Create an 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 uma conta Alibaba Cloud não têm nenhuma permissão por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.
|
API |
Ação |
Descrição |
|
PutObject |
|
Envia um objeto. |
|
|
Necessário se você especificar tags de objeto usando o cabeçalho |
|
|
|
Necessário se o cabeçalho |
|
|
|
Enviar uma string
O exemplo de código a seguir mostra como enviar 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");
Enviar 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 envio 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");