All Products
Search
Document Center

Object Storage Service:Conditional downloads (Browser.js SDK)

Last Updated:Mar 20, 2026

Conditional downloads let you attach preconditions to a GetObject request. OSS downloads the object only when the condition is met; otherwise, it returns an error without transferring any data.

Usage notes

  • When using bundlers such as Webpack or Browserify, install OSS SDK for Browser.js by running npm install ali-oss.

  • Configure CORS rules for your bucket before accessing it from a browser. Without CORS rules, the browser blocks the request. For details, see Installation.

  • Use temporary access credentials from Security Token Service (STS) to avoid exposing your AccessKey pair in browser code. The credentials consist of an AccessKey ID, an AccessKey secret, and a security token. For details, see Use STS for temporary access authorization.

Supported condition headers

Pass one or more of the following request headers in the headers option of client.get():

HeaderDownloads the object when...Returns if condition fails
If-Modified-SinceThe specified time is earlier than the object's last-modified time304 Not Modified
If-Unmodified-SinceThe specified time is the same as or later than the object's last-modified time412 Precondition Failed
If-MatchThe specified ETag matches the object's ETag412 Precondition Failed
If-None-MatchThe specified ETag does not match the object's ETag304 Not Modified

When multiple headers are specified, all conditions must be satisfied for the download to proceed.

Sample code

The following example initializes an OSS client with STS credentials and demonstrates each condition header. The upload button creates the test object; the download button applies the condition.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
</head>

<body>
  <button id='upload'>Upload</button>
  <button id='download'>Download</button>
  <!-- Import the SDK file. -->
  <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"></script>
  <script type="text/javascript">
      const client = new OSS({
         // Set region to the region where the bucket is located.
         // Example: if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
         region: 'yourRegion',
         authorizationV4: true,
         // Temporary AccessKey ID and AccessKey secret obtained from STS.
         accessKeyId: 'yourAccessKeyId',
         accessKeySecret: 'yourAccessKeySecret',
         // Security token obtained from STS.
         stsToken: 'yourSecurityToken',
         // Bucket name. Example: examplebucket.
         bucket: 'examplebucket',
      });

    const download = document.getElementById('download')
    const upload = document.getElementById('upload')

    // Upload the object.
    upload.addEventListener('click', () => {
      // Object content.
      const file = new Blob(['examplecontent'])
      // Full path of the object to upload. Example: exampledir/exampleobject.txt.
      const fileName = 'exampledir/exampleobject.txt'
      const result = client.put(fileName, file).then(r => console.log(r))
    })

    // Download the object with a condition header.
    // Uncomment one of the headers below to apply the corresponding condition.
    download.addEventListener('click', () => {
      client.get('exampledir/exampleobject.txt', {
        headers: {
          // If-Modified-Since: downloads the object only if it was modified after the specified time.
          // Returns 304 Not Modified if the object has not changed.
          "If-Modified-Since": new Date("1970-01-01").toGMTString()

          // If-Unmodified-Since: downloads the object only if it was not modified after the specified time.
          // Returns 412 Precondition Failed if the object has been modified.
          // "If-Unmodified-Since": new Date("1970-01-01").toGMTString()

          // If-Match: downloads the object only if its ETag matches the specified value.
          // Returns 412 Precondition Failed if the ETags do not match.
          // "If-Match": '5B3C1A2E0563E1B002CC607C****'

          // If-None-Match: downloads the object only if its ETag does not match the specified value.
          // Returns 304 Not Modified if the ETags match.
          // "If-None-Match": '5B3C1A2E0563E1B002CC607C****'
        },
      }).then(r => {
        if (r.content.length > 0) {
          const newBlob = new Blob([r.content], { type: r.res.headers['content-type'] });
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(newBlob)
          link.download = 'foo.txt'
          link.click()
          window.URL.revokeObjectURL(link.href)
        } else {
          console.log('Status code:', r.res.status)
          console.log('Condition not met — object was not downloaded.')
        }
      })
    })

  </script>
</body>

</html>

Replace the following placeholders with actual values:

PlaceholderDescriptionExample
yourRegionRegion where the bucket is locatedoss-cn-hangzhou
yourAccessKeyIdTemporary AccessKey ID from STSSTS.NUgY...
yourAccessKeySecretTemporary AccessKey secret from STSxXxXxX...
yourSecurityTokenSecurity token from STSCAIS...
examplebucketBucket namemy-bucket
5B3C1A2E0563E1B002CC607C****ETag of the object (for ETag-based conditions)Retrieved from the upload response or HeadObject

What's next

  • For the complete sample code, see GitHub.

  • For the underlying API operation, see GetObject.