Quick Start

Last updated: 2020-02-28 19:22:48

PDF

Download and install

Environmental dependence

  1. This SDK is only applicable to WeChat Mini Programs environment.
  2. Login Cloud Object Storage console After creating Bucket, get the name of Bucket and Region information .
  3. Login Access Management console Get your project SecretId and SecretKey.

For the meaning and obtaining methods of the names such as SecretId, SecretKey, Bucket, etc., which appear in this article, see COS terminology Information .

Install SDK

There are two ways to install Mini Program SDK: manual installation and npm installation. The specific installation methods are as follows.

Manual installation

Copy the Cos-wx-sdk-v5.js Go to your Mini Program code root, Directory, any path, and use the relative path import:

var COS = require('./lib/cos-wx-sdk-v5.js')

Npm installation

If the Mini Program code is packaged with webpack, you can install the dependency through npm:

npm install cos-wx-sdk-v5

Among them, Mini Program code is used. var COS = require('cos-wx-sdk-v5'); Carry on import.

Ready to go

Mini Program domain name whitelist configuration

Mini Program requests that COS needs to log in to WeChat Official Account Select Development-> Development Settings to configure the whitelist of domain names. SDK uses two interfaces:

  1. Cos.postObject uses the wx.uploadFile method.
  2. Other methods use the wx.request method.

You need to configure the COS domain name in the corresponding whitelist. There are two whitelist domain name formats:

  1. If it is a standard request, you can configure Bucket domain name as a whitelist domain name, for example:
    examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com .
  2. If Mini Program uses a lot of Bucket, you can choose to request COS, with suffix only when the SDK is instantiated. ForcePathStyle: true In this way, you need to configure a regional domain name as a whitelist, for example: cos.ap-guangzhou.myqcloud.com .

Initialization

var COS = require('./lib/cos-wx-sdk-v5.js')
var cos = new COS({
    // ForcePathStyle: true, // If multiple buckets are used, you can use suffixed requests to reduce the number of whitelisted domain names to be configured; and the region domain name will be used for requests
    getAuthorization: function (options, callback) {
        // Get a temporary key asynchronously
        wx.request({
            url: 'https://example.com/server/sts.php',
            data: {
                bucket: options.Bucket,
                region: options.Region,
            },
            dataType: 'json',
            success: function (result) {
                var data = result.data;
                var credentials = data.credentials;
                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    XCosSecurityToken: credentials.sessionToken,
                    ExpiredTime: data.expiredTime,
                });
            }
        });
    }
});

// Next you can use a COS instance to call a COS request
// TODO

Configuration Item

Usage Examples

Create a COS SDK instance, COS SDK supports the following formats:

  • Format 1 (recommended): the backend gives it to the front end by obtaining a temporary key, and the front end calculates the signature.
var cos = new COS({
    // Required parameters
    getAuthorization: function (options, callback) {
        // Server-side examples for JS and PHP: https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
        // For server-side examples for other programming languages, see the COS SDK for STS: https://github.com/tencentyun/qcloud-cos-sts-sdk
        // For the STS documentation, visit https://intl.intl.cloud.tencent.com/document/product/436/14048
        wx.request({
            url: 'https://example.com/server/sts.php',
            data: {
                // The required parameters can be obtained from options
            },
            success: function (result) {
                var data = result.data;
                var credentials = data.credentials;
                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    XCosSecurityToken: credentials.sessionToken,
                    ExpiredTime: data.expiredTime,
                });
            }
        });
    }
});

Temporary key generation and use can be found in Generating and Using Temporary Keys .

  • Format 2 (recommended): fine-grained control of Permission. The backend gives the temporary key to the frontend by obtaining the temporary key. The frontend reuses the temporary key only with the same request, and the backend can control Permission through fine-grained Scope.
var cos = new COS({
    // Required parameters
    getAuthorization: function (options, callback) {
        // Server-side example:https://github.com/tencentyun/qcloud-cos-sts-sdk/edit/master/scope.md
        wx.request({
            url: 'https://example.com/server/sts-scope.php',
            data: JSON.stringify(options.Scope),
            success: function (result) {
                var data = result.data;
                var credentials = data.credentials;
                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    XCosSecurityToken: credentials.sessionToken,
                    ExpiredTime: data.expiredTime,
                    ScopeLimit: true, // You need to set the fine-grained permission control to true to make sure that the key will only be reused for the same request
                });
            }
        });
    }
});

Temporary key generation and use can be found in Generating and Using Temporary Keys .

  • Format 3 (not recommended): the frontend needs to obtain the signature through getAuthorization before each request, and the backend uses a fixed key or temporary key to calculate the signature and return it to the frontend. This format is not easy to control by multipart upload and Permission. It is not recommended that you use this format.
var cos = new COS({
    // Required parameters
    getAuthorization: function (options, callback) {
        // The server obtains a signature. For more information, see the COS SDK for the corresponding programming language:https://intl.cloud.tencent.com/document/product/436/6474?from_cn_redirect=1
        // Note: This method involves security risks. The backend needs to strictly control the permissions through method and pathname, such as prohibiting `PUT` /
        wx.request({
            url: 'https://example.com/server/auth.php',
            data: JSON.stringify(options.Scope),
            success: function (result) {
                var data = result.data;
                callback({
                    Authorization: data.authorization,
                    // XCosSecurityToken: data.sessionToken, // If a temporary key is used, sessionToken needs to be passed to XCosSecurityToken
                });
            }
        });
    },
});
  • Format 4 (not recommended): the front end uses a fixed key to calculate the signature, which is suitable for front-end debugging. If you use this format, please avoid revealing the key.
var cos = new COS({
    SecretId: 'COS_SECRETID',
    SecretKey: 'COS_SECRETKEY',
});

Constructor parameter description

Parameter name Parameter description Type Required
SecretID User's SecretId String No
SecretKey Users' SecretKey, is recommended to be used only during front-end debugging to avoid Open key. String No
FileParallelLimit The number of concurrent files uploaded under the same instance. Default is 3. Number No
ChunkParallelLimit The number of concurrency of part of the same uploaded file. The default is 3. Number No
ChunkRetryTimes When copying multipart upload and part, the number of error retries is 3 by default (plus the first request for 4 requests) Number No
ChunkSize When multipart upload, the number of bytes per block. The default value is 1048576 (1MB). Number No
SliceSize When uploading a batch using uploadFiles, use multipart upload sliceUploadFile, if the file size is larger than this value, otherwise use the default value of 1048576 (1MB) for simple upload putObject,. Number No
CopyChunkParallelLimit The number of concurrency of multipart upload in the copy operation of part. The default is 20. Number No
CopyChunkSize When copying files using sliceCopyFile part, the size of each block is in bytes. Default is 10485760 (10MB). Number No
CopySliceSize When using sliceCopyFile part to copy files, if the file size is larger than this value, part will be used to copy sliceCopyFile, otherwise the default value of simple copy putObjectCopy, will be 10485760 (10MB). Number No
ProgressInterval The callback frequency of onProgress, the callback method of upload progress, in ms. Default is 1000. Number No
Protocol Protocol used when making the request, optional https:http: By default, the current page is determined to be http: When using http: Otherwise, use the https: String No
ServiceDomain When the getService method is called, the requested domain name, such as service.cos.myqcloud.com String No
Domain Customize the request domain name when calling the API that operates Bucket and the object. You can use templates, such as "{Bucket}.cos.{Region}.myqcloud.com" That is, when calling API, it will be replaced with the Bucket and Region passed in the parameters. String No
UploadQueueSize The maximum size of the upload queue. If the status of job is not waiting, checking or uploading, the upload queue will be cleaned. Default is 10000. Number No
ForcePathStyle The suffix mode is forced to send the request. In the suffix mode, the Bucket is placed in the pathname after the domain name, and the Bucket is added to the signature pathname calculation. The default is false. Boolean No
UploadCheckContentMd5 Force upload file verification Content-MD5, will request Body to calculate md5 for the file. Put it in the Content-MD5 field of header. Default is false. Boolean No
GetAuthorization Callback method for obtaining signature. This parameter is required if there is no SecretId or SecretKey. Function No

Function description of getAuthorization callback function description (using format 1)

getAuthorization: function(options, callback) { ... }

getAuthorization Callback Parameters

Parameter name Parameter description Type
OPTIONS Get the parameter object required by the temporary key Function
-Bucket Bucket's name. The naming rule is BucketName-APPID,. Here Enter's Bucket name must be in this format. String
-Region For the region where Bucket is located, please see the enumerated values. Regions and Access Domain Names String
Callback The return method after the completion of temporary key acquisition Function

After obtaining the temporary key, callback returns an object. The list of attributes of the object is as follows:

Attribute name Parameter description Type Required
TmpSecretId The tmpSecretId of the temporary key obtained String Yes
TmpSecretKey The tmpSecretKey of the temporary key obtained String No
XCosSecurityToken The sessionToken, of the obtained temporary key corresponds to the x-cos-security-token field of header String No
ExpiredTime The expiredTime, timeout of the obtained temporary key String No

Description of getAuthorization callback function (using format 2)

getAuthorization: function(options, callback) { ... }

getAuthorization Callback Parameters

Parameter name Parameter description Type
OPTIONS Get the parameter object required for the signature Object
-Method Currently requested Method Object
-Pathname Request path for signature calculation String
- key Object key (name of Object), the unique identity of the object in Bucket. For more information, please see Object Overview String
-Query The format of the currently requested query parameter object, {key: 'val'} Object
-Headers The format of the currently requested header parameter object, {key: 'val'} Object
Callback Callback after temporary key acquisition is completed Function

After the getAuthorization calculation is completed, the callback return parameters support two formats:
Format 1: return the authentication credential string Authorization.
Format 2: return an object. The list of object attributes is as follows:

Attribute name Parameter description Type Required
Authorization Calculated signature string String Yes
XCosSecurityToken The sessionToken, of the obtained temporary key corresponds to the x-cos-security-token field of header String No

Obtain authentication credential

The authentication of the instance credential can be controlled or obtained by the parameters passed during instantiation. There are three ways to obtain it:

  1. When instantiating, input SecretId and SecretKey, each time the signature is required, it is calculated internally by the instance.
  2. When instantiating, pass the getAuthorization callback, which is used to calculate the signature and return the signature to the instance each time.
  3. When instantiating, pass in the getSTS callback, and each time you need a temporary key to go back through this callback and return it to the instance, and use the temporary key to calculate the signature within the instance during each request.

The following are examples of some common interfaces. For more detailed initialization methods, see Demo Example.

Create Bucket

cos.putBucket({
    Bucket: 'examplebucket-1250000000',
    Region: 'ap-beijing',
}, function (err, data) {
    console.log(err || data);
});

If you need to create Bucket in Mini Program, but Bucket's name is unknown, you cannot configure Bucket's name as a domain name whitelist. You can use suffix calls. For more information, please see FAQs .

Query Bucket list

cos.getService(function (err, data) {
    console.log(data && data.Buckets);
});

Uploading Objects

Mini Program's upload API wx.uploadFile only supports POST requests, while SDK needs to use postObject to upload files. If Mini Program only needs to use the API for uploading files, it is recommended not to use import SDK,. For more information, please see simple example. Demo .

// First, select the file to get the temporary path
wx.chooseImage({
    count: 1, // Default value: 9
    sizeType: ['original'], // You can specify whether to use the original or compressed image. The original is used by default
    sourceType: ['album', 'camera'], // You can specify whether the source is album or camera. Both can be the source by default
    success: function (res) {
        var filePath = res.tempFiles[0].path;
        var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
        cos.postObject({
            Bucket: 'examplebucket-1250000000',
            Region: 'ap-beijing',
            Key: 'destination path/' + filename,
            FilePath: filePath,
            onProgress: function (info) {
                console.log(JSON.stringify(info));
            }
        }, function (err, data) {
            console.log(err || data);
        });
    }
});

Query object list

cos.getBucket({
    Bucket: 'examplebucket-1250000000',
    Region: 'ap-beijing',
    Prefix: 'exampledir/', // Pass in the prefix of the files to be listed
}, function (err, data) {
    console.log(err || data.Contents);
});

Download Object

This API is used to read the contents of the object. If you need to initiate a browser to download a file, you can obtain url through cos.getObjectUrl and then trigger the browser to download. For more information, please see Pre-signed URL Document.

cos.getObject({
    Bucket: 'examplebucket-1250000000',
    Region: 'ap-beijing',
    Key: 'exampleobject.txt',
}, function (err, data) {
    console.log(err || data.Body);
});

Delete Object

cos.deleteObject({
    Bucket: 'examplebucket-1250000000',
    Region: 'ap-beijing',
    Key: 'picture.jpg',
}, function (err, data) {
    console.log(err || data);
});