Todos os produtos
Search
Central de documentação

Object Storage Service:Append upload (Harmony SDK)

Última atualização: Sep 25, 2026

É possível acrescentar conteúdo a objetos do tipo appendable já existentes. Este tópico descreve como executar upload por append usando o Object Storage Service (OSS) SDK para Harmony 2.0.

Notas de uso

  • Para obter mais informações sobre regiões e endpoints, consulte Regions and endpoints.

  • Se o objeto ao qual você deseja acrescentar conteúdo não existir, um objeto appendable será criado ao chamar uma operação de upload por append.

  • Se o arquivo já existir:

    • Se o objeto for do tipo appendable e a posição especificada a partir da qual a operação de append se inicia for igual ao comprimento atual do objeto, o conteúdo será acrescentado ao final do objeto.

    • Se o objeto for do tipo appendable e a posição especificada a partir da qual a operação de append se inicia não for igual ao comprimento atual do objeto, o erro PositionNotEqualToLength será retornado.

    • Se o objeto não for do tipo appendable, o erro ObjectNotAppendable será retornado.

Permissões

Por padrão, uma conta da Alibaba Cloud tem permissões completas. Usuários RAM ou funções RAM vinculados a uma conta da Alibaba Cloud não têm nenhuma permissão por padrão. A conta da Alibaba Cloud ou o administrador da conta deve conceder permissões de operação por meio de RAM policies ou Bucket Policy.

API

Action

Description

AppendObject

oss:PutObject

Use esta operação para fazer upload de um objeto acrescentando-o a um objeto existente.

oss:PutObjectTagging

Ao fazer upload de um objeto por append, esta permissão é necessária caso você especifique tags de objeto por meio de x-oss-tagging.

Código de exemplo

O código a seguir apresenta um exemplo de upload por append:

import Client, {RequestError } from '@aliyun/oss';

// Create an OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID obtained from Security Token Service (STS).
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret obtained from STS.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the security token obtained from STS.
  securityToken: 'yourSecurityToken',
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

// Specify the name of the bucket.
const bucket = 'yourBucketName';
// Specify the name of the object to which you want to append content.
const key = 'yourObjectName';

/**
 * Append the content to an OSS object. 
 * Use the appendObject method to append data to a specific object in a specific bucket. 
 */
const appendObject = async () => {
  try {
    // Use the appendObject method to append data to a specific object in a specific bucket.
    // Do not specify the position parameter when you create an appendable object for the first time. Then, specify the position parameter when you perform the append upload operation.
    const res = await client.appendObject({
      bucket, // Specify the name of the bucket.
      key,    // Specify the name of the object.
      data: 'hello world' // Specify the data that you want to append. In this example, a simple string is appended.
    });

    // Display the append upload results.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Capture exceptions during the request.
    if (err instanceof RequestError) {
      // If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC.
      console.log('code: ', err.code); // The error code.
      console.log('message: ', err.message); // The error message.
      console.log('requestId: ', err.requestId); // The request ID.
      console.log('status: ', err.status); // The HTTP status code.
      console.log('ec: ', err.ec); // The EC.
    } else {
      // Display other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
};

// Call the appendObject function to perform the append upload operation.
appendObject();

Cenários comuns

Append a local file to an object

O código de exemplo a seguir apresenta como acrescentar um arquivo local a um objeto:

import Client, { RequestError } from '@aliyun/oss';
import { fileIo as fs } from '@kit.CoreFileKit';

// Create an OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID obtained from STS.
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret obtained from STS.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the security token obtained from STS.
  securityToken: 'yourSecurityToken',
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

// Specify the name of the bucket.
const bucket = 'yourBucketName';
// Specify the name of the object to which you want to append content.
const key = 'yourObjectName';

/**
 * Append content to the object using the local file path. 
 * Use the appendObject method to append the content of a local file to an object in a specific bucket. 
 */
const appendObjectByFile = async () => {
  // Open and read the local file.
  const file=await fs.open('yourFilePath', fs.OpenMode.READ_ONLY); // Specify the path of the local file.

  try {
    // Use the appendObject method to append the content of a local file to an object in a specific bucket.
    // Do not specify the position parameter when you create an appendable object for the first time. Then, specify the position parameter when you perform the append upload operation.
    const res = await client.appendObject({
      bucket, // Specify the name of the bucket.
      key,    // Specify the name of the object.
      data: file, // Specify the local file that you want to append.
    });

    // Display the append upload results.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Capture exceptions during the request.
    if (err instanceof RequestError) {
      // If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC.
      console.log('code: ', err.code); // The error code.
      console.log('message: ', err.message); // The error message.
      console.log('requestId: ', err.requestId); // The request ID.
      console.log('status: ', err.status); // The HTTP status code.
      console.log('ec: ', err.ec); // The EC.
    } else {
      // Display other unknown types of errors.
      console.log('unknown error: ', err);
    }
  } finally {
    // Close the local file after the operation is complete.
    await fs.close(file);
  }
};

// Call the appendObjectByFile function to perform the append upload operation.
appendObjectByFile();

Specify the position from which the append operation starts

O código de exemplo a seguir apresenta como especificar a posição a partir da qual a operação de append se inicia:

import Client, { RequestError, EHeaderKey } from '@aliyun/oss';

// Create an OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID obtained from STS.
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret obtained from STS.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the security token obtained from STS.
  securityToken: 'yourSecurityToken',
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

// Specify the name of the bucket.
const bucket = 'yourBucketName';
// Specify the name of the object to which you want to append content.
const key = 'yourObjectName';

/**
 * Append the content to an OSS object and specify the position from which the append operation starts. 
 * Use the appendObject method to append data blocks to a specific object in a specific bucket and specify the position from which the append operation starts. 
 */
const appendObjectWithPosition = async () => {
  try {
    // Call the appendObject method to start the first append upload to append the initial data block.
    const res = await client.appendObject({
      bucket, // Specify the name of the bucket.
      key,    // Specify the name of the object.
      data: 'first chunk data', // The first data block.
    });

    // Display the first append upload results.
    console.log(JSON.stringify(res));

    /* Obtain the position from which the next append operation starts.
    const nextAppendPosition = Number(res.origRes.headers[EHeaderKey.X_OSS_NEXT_APPEND_POSITION]);

    // Call the appendObject method to start the second append upload to append the second data block.
    const res1 = await client.appendObject({
      bucket, // Specify the name of the bucket.
      key,    // Specify the name of the object.
      data: 'second chunk data', // The second data block.
      position: nextAppendPosition, // The append position from which the second append starts.
    });

    // Display the second append upload results.
    console.log(JSON.stringify(res1));
  } catch (err) {
    // Capture exceptions during the request.
    if (err instanceof RequestError) {
      // If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC.
      console.log('code: ', err.code); // The error code.
      console.log('message: ', err.message); // The error message.
      console.log('requestId: ', err.requestId); // The request ID.
      console.log('status: ', err.status); // The HTTP status code.
      console.log('ec: ', err.ec); // The EC.
    } else {
      // Display other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
};

// Call the appendObjectWithPosition function to perform the append upload operation to append data blocks.
appendObjectWithPosition();