Todos os produtos
Search
Central de documentação

Object Storage Service:Append upload (Harmony SDK)

Última atualização: Jul 03, 2026

É possível acrescentar conteúdo a objetos anexáveis existentes. Este tópico descreve como realizar o upload por acréscimo usando o SDK do Object Storage Service (OSS) para Harmony 2.0.

Observações de uso

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

  • Caso o objeto ao qual você deseja acrescentar conteúdo não exista, um objeto anexável será criado durante a chamada da operação de upload por acréscimo.

  • Se o arquivo já existir:

    • Quando o objeto for anexável e a posição inicial especificada para o acréscimo for igual ao tamanho atual do objeto, o conteúdo será adicionado ao final dele.

    • Quando o objeto for anexável, mas a posição inicial especificada for diferente do tamanho atual do objeto, o erro PositionNotEqualToLength será retornado.

    • Se o objeto não for do tipo anexável, o sistema retornará o erro ObjectNotAppendable.

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não têm nenhuma permissão configurada inicialmente. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões operacionais necessárias por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

AppendObject

oss:PutObject

Esta operação permite fazer upload de um objeto acrescentando-o a um objeto existente.

oss:PutObjectTagging

Necessária quando tags de objeto são definidas via x-oss-tagging durante o upload por acréscimo.

Código de exemplo

O código abaixo demonstra como executar um upload por acréscimo:

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

Acrescentar um arquivo local a um objeto

O exemplo a seguir mostra como adicionar o conteúdo de 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();

Especificar a posição inicial do acréscimo

Este exemplo ilustra como definir a posição exata onde o acréscimo deve começar:

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();