Todos os produtos
Search
Central de documentação

Object Storage Service:Upload files (PHP SDK V1)

Última atualização: Jul 03, 2026

Este tópico descreve como fazer upload de objetos para um bucket com versionamento ativado.

Precauções

  • 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 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.

  • Para fazer upload de um objeto, você precisa da permissão oss:PutObject. Para mais informações, consulte Conceder permissões personalizadas a um usuário RAM.

Upload simples

Em buckets com versionamento ativado, o OSS gera uma string aleatória globalmente única como ID de versão para cada novo objeto enviado. Esse ID é retornado no campo x-oss-version-id do cabeçalho de resposta.

Se o versionamento estiver suspenso, o OSS atribui o valor "null" como ID de versão para novos uploads. Caso você envie um objeto com o mesmo nome, o novo objeto substituirá o anterior. Nesse cenário, o objeto terá apenas uma versão, identificada como "null".

O código a seguir mostra como executar um 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;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The Endpoint of the China (Hangzhou) region is used as an example. Replace it with the actual Endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name. Example: example/test.txt.
$object = "<yourObjectName>";
$content = "hello world";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

try {
    // Upload an object to a versioned bucket.
    $ret = $ossClient->putObject($bucket, $object, $content);

    // View the version information of the object.
    print("versionId:" .$ret[OssClient::OSS_HEADER_VERSION_ID]);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");

Para mais informações sobre uploads simples, consulte PutObject.

Upload por acréscimo

Ao acrescentar dados a um objeto (AppendObject) em um bucket com versionamento, observe o seguinte:

  • A operação AppendObject só é permitida em objetos cuja versão atual seja do tipo Appendable.

  • Não é possível executar AppendObject se a versão atual do objeto não for do tipo Appendable, como em Normal Objects ou Delete Markers. A operação também falhará caso apenas as versões históricas do objeto sejam do tipo Appendable.

  • Ao executar AppendObject em um objeto cuja versão atual é Appendable, o OSS não cria uma versão histórica para esse objeto.

  • Se você executar uma operação PutObject ou DeleteObject em um objeto Appendable, o OSS salvará o objeto atual como uma versão histórica. Depois disso, não será mais possível acrescentar dados a esse objeto.

O código a seguir mostra como executar um upload por acréscimo:

<?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;

// Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The Endpoint of the China (Hangzhou) region is used as an example. Replace it with the actual Endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
// After the first, second, and third append uploads, the file content is "Hello OSS", "Hi OSS", and "OSS OK" respectively.
$content_array = array('Hello OSS', 'Hi OSS', 'OSS OK');
try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    // The first append upload. The position for the first append is 0. The return value is the position for the next append. The position for subsequent appends is the length of the file before the append.
    $position = $ossClient->appendObject($bucket, $object, $content_array[0], 0);    
    $position = $ossClient->appendObject($bucket, $object, $content_array[1], $position);   
    $position = $ossClient->appendObject($bucket, $object, $content_array[2], $position);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");

Para mais detalhes sobre uploads por acréscimo, consulte AppendObject.

Upload multipartido

Em buckets com versionamento, use a operação CompleteMultipartUpload para concluir um upload multipartido. O OSS gera um ID de versão exclusivo para o objeto completo e o retorna no campo x-oss-version-id do cabeçalho de resposta.

O código a seguir mostra como executar um upload multipartido:

<?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 running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The Endpoint of the China (Hangzhou) region is used as an example. Replace it with the actual Endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
// Specify the full path of the local file.
$uploadFile = "<yourLocalFile>";

/**
 *  Step 1: Initialize a multipart upload event and obtain the uploadId.
 */
try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    // The uploadId is returned. The uploadId is the unique identifier of the multipart upload event. You can use the uploadId to perform related operations, such as aborting or querying the multipart upload.
    $uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
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(
        // The file to upload.
        $ossClient::OSS_FILE_UPLOAD => $uploadFile,
        // Set the part number.
        $ossClient::OSS_PART_NUM => ($i + 1),
        // Specify the start position of the part to upload.
        $ossClient::OSS_SEEK_TO => $fromPos,
        // Specify the file length.
        $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
        // Specifies whether to enable MD5 validation. true: enable. false: disable.
        $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
    );
    // Enable MD5 validation.
    if ($isCheckMd5) {
        $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
        $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
    }
    try {
        // Upload the part.
        $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 upload.
 */
try {
    // When you call the completeMultipartUpload operation, you must provide all valid $uploadParts. After OSS receives the submitted $uploadParts, it verifies the validity of each part. After all parts are verified, OSS combines them into a complete file.
    $ret = $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
    // View the version information of the object.
    print("versionId:" .$ret[OssClient::OSS_HEADER_VERSION_ID]);
}  catch(OssException $e) {
    printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");   

Para mais informações sobre uploads multipartidos, consulte operações como InitiateMultipartUpload, UploadPart e CompleteMultipartUpload.