Todos os produtos
Search
Central de documentação

Object Storage Service:Upload simples (Harmony SDK)

Última atualização: Sep 22, 2026

Este tópico descreve o método de upload simples, uma forma prática de enviar rapidamente um único arquivo ao OSS.

Precauções

Para mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regions and endpoints.

Permissões

Por padrão, uma conta da Alibaba Cloud detém permissões completas. Usuários RAM ou funções RAM vinculados a essa conta não possuem nenhuma permissão inicialmente. A conta da Alibaba Cloud ou o administrador responsável deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Envia um objeto.

oss:PutObjectTagging

Necessária ao enviar. Especifique os rótulos do objeto usando o cabeçalho x-oss-tagging durante o processo.

kms:GenerateDataKey

Obrigatória ao enviar. Defina o cabeçalho X-Oss-Server-Side-Encryption: KMS como KMS no momento do upload do objeto.

kms:Decrypt

Código de exemplo

Utilize o código a seguir para enviar uma string como arquivo ao bucket de destino.

Importante

Caso você envie um objeto para um bucket que já contém outro com o mesmo nome, o novo arquivo substituirá o anterior, desde que suas credenciais possuam as permissões necessárias.

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

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the security token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

const bucket = 'yourBucketName'; // Replace with the name of the bucket you want to use.

const key = 'yourObjectName'; // Replace with the name of the object (file) you want to upload.

const putObject = async () => {
  try {
    // Call the putObject method to upload data to the specified bucket and key, passing the data as a parameter.
    const res = await client.putObject({
      bucket, // The bucket name.
      key, // The object (file) name.
      data: 'hello world' // The data to upload. In this case, a simple string.
    });

    // Print the upload result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch exceptions that occur during the request.
    if (err instanceof RequestError) {
      // If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
      console.log('code: ', err.code);
      console.log('message: ', err.message);
      console.log('requestId: ', err.requestId);
      console.log('status: ', err.status);
      console.log('ec: ', err.ec);
    } else {
      // Print other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
}

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

Cenários

Enviar um arquivo local

Use o código a seguir para transferir um arquivo do seu computador para o bucket de destino.

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

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the security token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

// Specify the name of the bucket to operate on. Replace with your actual bucket name.
const bucket = 'yourBucketName';
// Specify the name of the object (file) to upload. Replace with your actual object name.
const key = 'yourObjectName';

/**
 * Upload an object to OSS from a file path.
 * Use the putObject method to upload a local file to the specified bucket and key.
 */
const putObjectByFile = async () => {
  // Open the local file for reading.
  const file = await fs.open('yourFilePath', fs.OpenMode.READ_ONLY); // Replace with the actual file path.

  try {
    // Call the putObject method to upload the file to the specified bucket and key.
    const res = await client.putObject({
      bucket, // The bucket name.
      key,    // The object (file) name.
      data: file, // The file data to upload.
    });

    // Print the upload result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch exceptions that occur during the request.
    if (err instanceof RequestError) {
      // If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
      console.log('code: ', err.code); // Error code
      console.log('message: ', err.message); // Error message
      console.log('requestId: ', err.requestId); // Request ID
      console.log('status: ', err.status); // HTTP status code
      console.log('ec: ', err.ec); // Error code
    } else {
      // Print other unknown types of errors.
      console.log('unknown error: ', err);
    }
  } finally {
    // Make sure to close the file after the operation is complete.
    await fs.close(file);
  }
};

// Call the putObjectByFile function to perform the file upload operation.
putObjectByFile();

Enviar um arquivo e definir a respectiva classe de armazenamento

Execute o código abaixo para carregar um arquivo no bucket e definir a classe de armazenamento desejada.

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

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the security token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

// Specify the name of the bucket to operate on. Replace with your actual bucket name.
const bucket = 'yourBucketName';
// Specify the name of the object (file) to upload. Replace with your actual object name.
const key = 'yourObjectName';

/**
 * Upload an object and specify its storage class.
 * Use the putObject method to upload data to the specified bucket and key, and set the storage class to ARCHIVE.
 */
const putObjectWithStorageClass = async () => {
  try {
    // Call the putObject method to upload data and specify the storage class as ARCHIVE.
    const res = await client.putObject({
      bucket, // The bucket name.
      key,    // The object (file) name.
      data: 'hello world', // The data to upload. In this case, a simple string.
      storageClass: EStorageClass.ARCHIVE, // Specify the storage class as ARCHIVE.
    });

    // Print the upload result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch exceptions that occur during the request.
    if (err instanceof RequestError) {
      // If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
      console.log('code: ', err.code); // Error code
      console.log('message: ', err.message); // Error message
      console.log('requestId: ', err.requestId); // Request ID
      console.log('status: ', err.status); // HTTP status code
      console.log('ec: ', err.ec); // Error code
    } else {
      // Print other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
};

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

Enviar um arquivo e definir as respectivas permissões de acesso

Adote o código a seguir para fazer o upload de um arquivo ao bucket e configurar as permissões de acesso.

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

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the security token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

// Specify the name of the bucket to operate on. Replace with your actual bucket name.
const bucket = 'yourBucketName';
// Specify the name of the object (file) to upload. Replace with your actual object name.
const key = 'yourObjectName';

/**
 * Upload an object and set its access permissions.
 * Use the putObject method to upload data to the specified bucket and key, and set the object's access permissions to PRIVATE.
 */
const putObjectWithObjectAcl = async () => {
  try {
    // Call the putObject method to upload data and set the object's access permissions to PRIVATE.
    const res = await client.putObject({
      bucket, // The bucket name.
      key,    // The object (file) name.
      data: 'hello world', // The data to upload. In this case, a simple string.
      objectAcl: EObjectAcl.PRIVATE, // Set the object's access permissions to PRIVATE.
    });

    // Print the upload result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch exceptions that occur during the request.
    if (err instanceof RequestError) {
      // If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
      console.log('code: ', err.code); // Error code
      console.log('message: ', err.message); // Error message
      console.log('requestId: ', err.requestId); // Request ID
      console.log('status: ', err.status); // HTTP status code
      console.log('ec: ', err.ec); // Error code
    } else {
      // Print other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
};

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