Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Quick Start (Browser.js SDK)

Son Güncelleme:Oct 01, 2026

Bu konuda, nesneleri yükleme, indirme ve sorgulama gibi işlemleri gerçekleştirmek için Browser.js için OSS SDK'nın nasıl kullanılacağı açıklanmaktadır.

Ön koşullar

  • Browser.js için OSS SDK yüklenmiştir. Daha fazla bilgi için bkz. Yükleme.

  • Paket için bir çapraz kaynak paylaşımı (CORS) kuralı yapılandırılmıştır. Daha fazla bilgi için bkz. Yükleme.

Kullanım notları

  • Browser.js için OSS SDK, tarayıcıda paketle ilgili işlemleri desteklemez. Bu SDK yalnızca PutObject ve GetObject gibi nesneyle ilgili işlemleri destekler.

  • Browser.js için OSS SDK çoğunlukla tarayıcılarda kullanılır. AccessKey çiftinizin açığa çıkmasını önlemek için OSS'ye erişirken Güvenlik Belirteci Hizmeti (STS) üzerinden elde edilen geçici erişim kimlik bilgilerini kullanmanızı öneririz.

    Geçici erişim kimlik bilgileri bir AccessKey çifti ve bir güvenlik belirtecinden oluşur. AccessKey çifti, bir AccessKey ID ve bir AccessKey Secret içerir. Geçici erişim kimlik bilgilerini edinme hakkında daha fazla bilgi için bkz. Geçici erişim yetkilendirmesi için STS kullanma.

Yaygın işlemler

Bu bölümde, Browser.js için OSS SDK ile gerçekleştirilen yaygın işlemler açıklanmaktadır.

STS sunucusu oluşturun ve istemciden geçici yetkilendirme bilgilerini alın

  1. Bir STS sunucusu oluşturun.

    STS sunucusu oluşturmanıza yardımcı olmak için OSS aşağıdaki dillerde SDK'lar sunar:

    Önemli

    Yukarıdaki demo uygulamalar yalnızca referans amaçlıdır. Üretim ortamında kimlik doğrulama ve diğer özellikler için gerekli kodu kendiniz geliştirmelisiniz.

  2. STS geçici yetkilendirme bilgilerini almak için tarayıcıdan STS sunucusuna istek gönderin.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
      <body>
        <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
        <script type="text/javascript">
          // OSS.urllib is the logic encapsulated in the SDK for sending requests. You can use any request library to send requests to your_sts_server.
          // Replace your_sts_server with the IP address or domain name of the STS server that you set up in Step 1.
          OSS.urllib.request(
            "your_sts_server",
            { method: "GET" },
            (err, response) => {
              if (err) {
                return alert(err);
              }
              try {
                result = JSON.parse(response);
              } catch (e) {
                errmsg = "parse sts response info error: " + e.message;
                return alert(errmsg);
              }
              console.log(result);
            }
          );
        </script>
      </body>
    </html>
                                

Nesneleri yükleyin

Bir dosya yüklemek için multipartUpload yöntemini çağırabilirsiniz.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="submit">Upload</button>
    <input id="file" type="file" />
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // 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: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey ID and AccessKey secret obtained from STS.
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token obtained from STS.
        stsToken: "yourSecurityToken",
        // Specify the bucket name, for example, examplebucket.
        bucket: "examplebucket",
      });

      const headers = {
        // Specify the caching behavior of the web page when the object is downloaded.
        "Cache-Control": "no-cache",
        // Specify the name of the object when it is downloaded.
        "Content-Disposition": "example.txt",
        // Specify the expiration time in milliseconds.
        Expires: "1000",
        // Specify the storage class of the object.
        "x-oss-storage-class": "Standard",
        // Specify tags for the object. You can specify multiple tags.
        "x-oss-tagging": "Tag1=1&Tag2=2",
        // Specify whether to overwrite an object that has the same name when you initialize a multipart upload. A value of true indicates that overwriting is prohibited.
        "x-oss-forbid-overwrite": "true",
      };

      // Specify the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
      const name = "exampleobject.txt";
      // Get the DOM.
      const submit = document.getElementById("submit");
      const options = {
        // Obtain the multipart upload progress, checkpoint, and return value.
        progress: (p, cpt, res) => {
          console.log(p);
        },
        // Set the number of parts to upload concurrently.
        parallel: 4,
        // Set the part size. The default value is 1 MB. The minimum value is 100 KB. The maximum value is 5 GB. The size of the last part can be smaller than 100 KB.
        partSize: 1024 * 1024,
        // headers,
        // Custom metadata. You can obtain the metadata of the object by calling the HeadObject operation.
        meta: { year: 2020, people: "test" },
        mime: "text/plain",
      };

      // Add a listener to the button.
      submit.addEventListener("click", async () => {
        try {
          const data = document.getElementById("file").files[0];
          // Perform multipart upload.
          const res = await client.multipartUpload(name, data, {
            ...options,
            // Set the upload callback.
            // If no callback server is involved, delete the callback settings.
            callback: {
              // Set the server address for the callback request.
              url: "http://examplebucket.aliyuncs.com:23450",
              // Set the Host value in the header of the callback request. This is the Host value configured on your server.
              host: "yourHost",
              /* eslint no-template-curly-in-string: [0] */
              // Set the value of the request body when a callback is initiated.
              body: "bucket=${bucket}&object=${object}&var1=${x:var1}",
              // Set the Content-Type of the callback request.
              contentType: "application/x-www-form-urlencoded",
              customValue: {
                // Set custom parameters for the callback request.
                var1: "value1",
                var2: "value2",
              },
            },
          });
          console.log(res);
        } catch (err) {
          console.log(err);
        }
      });
    </script>
  </body>
</html>

Nesneleri indirin

OSS, bir nesnenin indirme bağlantısı olarak imzalı bir URL oluşturur. Nesneyi indirmek için bu bağlantıyı kullanabilirsiniz.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!-- Import the SDK file -->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      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 obtained from STS. 
        stsToken: "yoursecurityToken",
        // Specify the name of the bucket. 
        bucket: "examplebucket",
      });

      // Set the response header to automatically download an object by using the URL, and set the name of the local file after the object is downloaded. 
      const filename = "examplefile.txt";
      const response = {
        "content-disposition": `attachment; filename=${encodeURIComponent(
          filename
        )}`,
      };
      // Specify the full path of the object. Do not include the bucket name in the full path. 
      const url = client.signatureUrl("exampleobject.txt", { response });
      console.log(url);
    </script>
  </body>
</html>

Nesneleri listeleyin

Aşağıdaki örnek kod, nesnelerin nasıl listeleneceğini gösterir:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
  </head>
  <body>
    <script>      
      const client = new OSS({
        // Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from Security Token Service (STS).
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // The security token (SecurityToken) obtained from STS.
        stsToken: 'yourSecurityToken',
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
      });

      async function list(dir) {
        try {
          // By default, a maximum of 1,000 files are returned.
          let result = await client.list();
          console.log(result);

          // Continue to obtain the file list starting from the file that follows the last file read in the previous list operation.
          if (result.isTruncated) {
            result = await client.list({ marker: result.nextMarker });
          }

          // List files that have the prefix 'ex'.
          result = await client.list({
            prefix: "ex",
          });
          console.log(result);

          // List files that have the prefix 'ex' and whose names come after 'example' in alphabetical order.
          result = await client.list({
            prefix: "ex",
            marker: "example",
          });
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      list();
    </script>
  </body>
</html>