Tencent Cloud Cloud Object Storage (COS) JavaScript SDK

repository·master·Indexed 43 days ago

https://github.com/tencentyun/cos-js-sdk-v5

Official JavaScript SDK (v1.10.1) for Tencent Cloud Object Storage (COS). It enables web applications to interact with COS buckets for file uploading, downloading, and management using the XML API. Features include support for Client Side Post (CSP) mode, automatic chunked uploading via uploadFile, and secure authentication using temporary credentials (STS) or a getAuthorization callback.

Tokens
15K
Snippets
45
Records
51
Agent score
56%

What's inside Tencent Cloud COS JS SDK

  1. Implement secure signature calculation via backend

    master

    To prevent exposing SecretId and SecretKey in the frontend, do not calculate signatures on the client side. Instead, implement the signature calculation process on your backend server. The frontend should request the signature from your backend via an AJAX call.

    When deploying to production, ensure your backend signature service includes your own application's permission/authentication checks.

  2. Understand the getAuthorization callback

    master

    When using the getAuthorization callback, the SDK provides an options object containing the context of the current request. You must call the callback with either a signature string or an object containing the Authorization field.

    options object properties:

    • Method: The current HTTP request method.
    • Key: The object key (file name) in the bucket.
    • Query: The query parameters object {key: 'val'}.
    • Headers: The request headers object {key: 'val'}.

    callback return values:

    • A string: The Authorization header value.
    • An object: { Authorization: '...' }.
  3. Determine allowed operations for signature logic

    master

    When implementing custom signature validation or permission logic, you can use the following rules to determine if an operation is allowed based on the pathname, method, and presence of specific query parameters. This is useful for verifying if a request matches specific COS operations like multipart uploads, simple uploads, or permission modifications.

    var exist = function (obj, key) {
        return obj[key] === undefined;
    };
  4. Download files in the browser

    master

    To download a file in a browser, first obtain the URL using cos.getObjectUrl. You can then trigger the download using several methods:

    1. Direct Window Open: Append response-content-disposition=attachment to the URL to force a download.
    2. Hidden iframe: Set the src of a hidden iframe to the download URL.
    3. HTML5 download attribute: Use an <a> tag with the download attribute (note: compatibility varies in older browsers).

    Example: Force download via URL parameter

    cos.getObjectUrl({
        Method: 'PUT',
        Key: '1.jpg',
        Sign: true
    }, function (err, data) {
        if (!err) {
            // Append parameter to force download
            var downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment';
            window.open(downloadUrl);
        }
    });
  5. Upload files using COS JavaScript SDK CSP mode

    master

    To perform file uploads using the CSP pattern, initialize the COS instance with a getAuthorization function that fetches signatures from your backend, then use sliceUploadFile for the upload process.

    Steps:

    1. Create an HTML file with a file input.
    2. Include the cos-js-sdk-v5.min.js script.
    3. Configure the Bucket and Region.
    4. Implement getAuthorization to call your backend endpoint (e.g., a PHP or Node.js script) that returns the signature JSON.
    5. Use cos.sliceUploadFile to handle the upload (this method supports chunked uploading).
    <input id="file-selector" type="file">
    <script src="dist/cos-js-sdk-v5.min.js"></script>
    <script>
    var Bucket = 'test-1250000000';
    var Region = 'ap-guangzhou';
    
    // Initialize instance
    var cos = new COS({
        CompatibilityMode: true,
        ServiceDomain: 'http://cos.default.xxx.com', // Replace with getService domain
        Domain: 'http://{Bucket}.cos.{Region}.xxx.com', // Replace with API domain template
        getAuthorization: function (options, callback) {
            // Request signature from your backend
            var url = './auth-json.php?method=' + options.Method + '&path=' + encodeURIComponent('/' + options.Key);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onload = function (e) {
                callback(e.target.responseText);
            };
            xhr.send();
        },
    });
    
    // Listen for file selection
    document.getElementById('file-selector').onchange = function () {
        
        var file = this.files[0];
        if (!file) return;
    
        // Chunked upload file
        cos.sliceUploadFile({
            Bucket: Bucket,
            Region: Region,
            Key: file.name,
            Body: file,
        }, function (err, data) {
            console.log(err, data);
        });
    
    };
    </script>
  6. Prerequisites for using COS JS SDK

    master

    Before using the SDK, ensure the following requirements are met:

    1. Browser Support: The browser must support basic HTML5 features for AJAX file uploads and MD5 calculation.
    2. COS Resources: Create a bucket in the COS Console. You will need the Bucket name (format: bucketname-appid) and the Region.
    3. Credentials: Obtain your SecretId and SecretKey from the API Key Management console.
    4. CORS Configuration: Configure Cross-Origin Resource Sharing (CORS) rules on your bucket in the COS console to allow requests from your web domain.
  7. Prepare for COS JavaScript SDK CSP development

    master

    To use the COS JavaScript SDK with Client Side Post (CSP) mode, complete the following prerequisites:

    1. Browser Support: Ensure the browser supports basic HTML5 features for AJAX file uploads and MD5 calculation.
    2. COS Credentials: Create a bucket in the Tencent Cloud COS console to obtain your Bucket (bucket name) and Region (region name).
    3. Access Keys: Retrieve your SecretId and SecretKey from the console's Key Management section.
    4. CORS Configuration: Configure Cross-Origin Resource Sharing (CORS) rules on your bucket in the COS console to allow requests from your web domain.
  8. Run the local demo

    master

    To run the full demonstration including the STS server:

    1. Clone the repository: git clone cos-js-sdk-v5.
    2. Install dependencies: cd cos-js-sdk-v5 && npm install.
    3. Configure the STS server: Edit server/sts.js or server/sts.php with your secretId, secretKey, bucket, and region. Ensure allowPrefix and allowActions are set correctly.
    4. Configure the frontend: Edit demo/index.html to set the correct Bucket and Region.
    5. Start the server: npm run server.
    6. Access the demo: Open http://127.0.0.1:3000/ in your browser.
    git clone cos-js-sdk-v5
    cd cos-js-sdk-v5
    npm install
    # ... configure files ...
    npm run server
  9. Configure COS constructor options

    master

    The new COS({}) constructor accepts the following configuration options:

    ParameterDescriptionTypeDefault
    SecretIdUser's SecretIdString-
    SecretKeyUser's SecretKey (Avoid using in production)String-
    FileParallelLimitNumber of concurrent file uploads per instanceNumber3
    ChunkParallelLimitNumber of concurrent chunk uploads per fileNumber3
    ChunkSizeSize of each chunk in bytesNumber1048576 (1MB)
    ProgressIntervalFrequency of onProgress callback in msNumber1000
    ProtocolCustom request protocol (https: or http:)StringMatches page protocol
    getAuthorizationCallback to fetch signature (Required if no SecretId/SecretKey provided)Function-