All Products
Search
Document Center

Object Storage Service:Upload objects

Last Updated:Mar 15, 2024

This topic describes how to upload objects to a versioning-enabled bucket in Object Storage Service (OSS).

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

  • To upload an object, you must have the oss:PutObject permission. For more information, see Attach a custom policy to a RAM user.

Simple upload

When an object is uploaded to a versioning-enabled bucket, OSS generates a random string as the globally unique version ID of the object and returns the x-oss-version-id header in the response.

When an object is uploaded to a versioning-suspended bucket, OSS generates a version ID of null for the uploaded object. In this case, if you upload an object that has the same name as the existing object in the bucket, the existing object is overwritten.

The following sample code provides an example on how to perform a simple upload:

<?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 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();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt. 
$object = "<yourObjectName>";
$content = "hello world";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

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

    // Display the version ID 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");

For more information, see PutObject.

Append upload

When you upload an object to a versioned bucket by using append upload, take note of the following items:

  • You can call the AppendObject operation only on an object whose current version is an appendable object.

  • The AppendObject operation cannot be called on an object whose current version is not an appendable object or a previous version that is an appendable object. For example, you cannot call the operation on an object whose current version is a normal object or a delete marker.

  • When you call the AppendObject operation on an object whose current version is an appendable object, OSS does not generate a previous version for the object.

  • When you call the PutObject or DeleteObject operation on an object whose current version is an appendable object, OSS stores the appendable object as a previous version and prevents the object from being further appended.

The following sample code provides an example on how to perform an append upload:

<?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 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();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
// Specify that the object content obtained after the first append upload, second append upload, and third append upload 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,
    );
    $ossClient = new OssClient($config);

    // Perform the first append upload. The position for the first append upload is 0, and the position for the next append upload is included in the response. The position from which the next append upload starts is the current length of the object. 
    $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");

For more information about append uploads, see AppendObject.

Multipart upload

If you call the CompleteMultipartUpload operation to complete the multipart upload task for an object that you upload to a versioned bucket, OSS generates a unique version ID for the uploaded object and returns the x-oss-version-id header in the response.

The following sample code provides an example on how to perform a multipart upload:

<?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();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
// Specify the full path of the local file that you want to upload. 
$uploadFile = "<yourLocalFile>";

/**
 * Step 1: Initiate a multipart upload task and obtain the upload ID. 
 */
try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

    // Obtain the upload ID. The upload ID uniquely identifies the multipart upload task. You can use the upload ID to perform operations, such as canceling or querying the multipart upload task. 
    $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(
        // Upload the object. 
        $ossClient::OSS_FILE_UPLOAD => $uploadFile,
        // Specify part numbers. 
        $ossClient::OSS_PART_NUM => ($i + 1),
        // Specify the position from which the multipart upload task starts. 
        $ossClient::OSS_SEEK_TO => $fromPos,
        // Specify the object length. 
        $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
        // Specify whether to enable MD5 verification. A value of true indicates that MD5 verification is enabled. A value of false indicates that MD5 verification is disabled. 
        $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
    );
    // Enable 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");
}
// The $uploadParts parameter is an array that consists of the ETag and PartNumber parameters of each part. 
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
    $uploadParts[] = array(
        'PartNumber' => ($i + 1),
        'ETag' => $eTag,
    );
}
/**
 * Step 3: Complete the multipart upload task. 
 */
try {
    // All valid values of the $uploadParts parameter are required for the CompleteMultipartUpload operation. After OSS receives the values of the $uploadParts parameter, OSS verifies all parts one by one. If all the parts pass the verification, OSS combines these parts together into a complete object. 
    $ret = $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
    // Display the version ID of the uploaded 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");   

For more information about API operations in a multipart upload task, see InitiateMultipartUpload, UploadPart, and CompleteMultipartUpload.