Todos os produtos
Search
Central de documentação

Object Storage Service:Simple upload (Harmony SDK)

Última atualização: Jul 03, 2026

Este tópico descreve o método de upload simples, uma forma direta e rápida de enviar um único arquivo para o OSS.

Precauções

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

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não possuem permissões iniciais. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Envia um objeto.

oss:PutObjectTagging

Necessário se você especificar tags de objeto com o cabeçalho x-oss-tagging durante o upload.

kms:GenerateDataKey

Obrigatório quando o cabeçalho X-Oss-Server-Side-Encryption: KMS estiver definido como KMS no upload do objeto.

kms:Decrypt

Código de exemplo

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

Importante

Se você enviar um objeto para um bucket que já contém outro com o mesmo nome, o novo objeto substituirá o existente, desde que você tenha as permissões de acesso 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 enviar um arquivo local 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 especificar sua classe de armazenamento

Use o código a seguir para enviar um arquivo ao bucket de destino e definir sua classe de armazenamento.

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 especificar suas permissões de acesso

Use o código a seguir para enviar um arquivo ao bucket de destino e definir suas 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();