Todos los productos
Search
Centro de documentos

Object Storage Service:Carga simple (SDK de Browser.js)

Última actualización: Sep 25, 2026

En este tema se describe cómo llamar a la operación PutObject para cargar archivos, datos BLOB o búferes en Object Storage Service (OSS). Las funciones de progreso no se pueden usar en las cargas simples.

Requisitos previos

El SDK de OSS para Browser.js ya está instalado. Para obtener más información, consulte Installation.

Notas de uso

  • Cuando use herramientas de empaquetado como Webpack y Browserify, instale el SDK de OSS para Browser.js mediante la ejecución del comando npm install ali-oss.

  • Si desea acceder a un bucket de OSS desde un navegador, pero el bucket no tiene reglas CORS configuradas, el navegador rechazará la solicitud. Por lo tanto, debe configurar reglas CORS en el bucket para poder acceder a él desde un navegador. Para obtener más información, consulte Installation.

  • En la mayoría de los casos, el SDK de OSS para Browser.js se usa dentro de navegadores. Para evitar que su par de AccessKey quede expuesto, se recomienda usar credenciales de acceso temporales obtenidas de Security Token Service (STS) para acceder a OSS.

    Las credenciales de acceso temporales constan de un par de AccessKey y un token de seguridad. El par de AccessKey incluye un AccessKey ID y un AccessKey secret. Para obtener más información sobre cómo conseguir credenciales de acceso temporales, consulte Use STS for temporary access authorization.

Permisos

De forma predeterminada, una cuenta de Alibaba Cloud tiene todos los permisos. Los usuarios o roles de RAM asociados a una cuenta de Alibaba Cloud no tienen ningún permiso de manera predeterminada. La cuenta de Alibaba Cloud o el administrador de la cuenta deben otorgar los permisos de operación mediante RAM policies o Bucket Policy.

API

Action

Descripción

PutObject

oss:PutObject

Carga un objeto.

oss:PutObjectTagging

Obligatorio si especifica etiquetas de objeto mediante el encabezado x-oss-tagging al cargar un objeto.

kms:GenerateDataKey

Obligatorio si el encabezado X-Oss-Server-Side-Encryption: KMS se establece en KMS al cargar un objeto.

kms:Decrypt

Código de ejemplo

Nota

BLOB (Binary Large Object) es un objeto binario grande.

A continuación se muestra un ejemplo de código para cargar datos en un objeto llamado exampleobject.txt, ubicado en el directorio exampledir del bucket examplebucket:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <input id="file" type="file" />
    <button id="upload">Upload an Object</button>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
    <script>
      const client = new OSS({
        // 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: "yourRegion",
        authorizationV4: true,
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // Specify the security token that you obtained from STS. 
        stsToken: "yourSecurityToken",
        // Specify the name of the bucket. 
        bucket: "examplebucket",
      });

      // Select the local file from the drop-down list. Example: <input type="file" id="file" />. 
      let data;
      // Create and specify the Blob data. 
      //const data = new Blob(['Hello OSS']);
      // Create an OSS buffer and specify the content of the OSS buffer. 
      //const data = new OSS.Buffer(['Hello OSS']);

      const upload = document.getElementById("upload");

      async function putObject(data) {
        try {
          // Specify the full path of the object. Do not include the bucket name in the full path. 
          // Specify the object name or the full path of the object to upload data to the current bucket or a specific directory in the bucket. For example, set the object name to exampleobject.txt or the path of the object to exampledir/exampleobject.txt. 
          // You can set the data to files, Blob data, or OSS buffers. 
          const options = {
            meta: { temp: "demo" },
            mime: "json",
            headers: { "Content-Type": "text/plain" },
          };
          const result = await client.put("examplefile.txt", data, options);
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      upload.addEventListener("click", () => {
        const data = file.files[0];
        putObject(data);
      });
    </script>
  </body>
</html>

Preguntas frecuentes

¿Se puede obtener el progreso de una carga simple?

No. El progreso de carga solo está disponible para multipart upload (Browser.js SDK) y resumable upload (Browser.js SDK).

Referencias

  • Para consultar el código de ejemplo completo de una carga simple, revise el ejemplo de GitHub.

  • Para obtener más información sobre la operación de API de carga simple, consulte PutObject.