Help Center> Object Storage Service> Best Practices> Uploading Data from Mini Programs to OBS
Updated on 2024-01-15 GMT+08:00

Uploading Data from Mini Programs to OBS

Context

Mini programs are now popular in a variety of scenarios. Uploading files to OBS through a mini program becomes a hot topic. In this section, an example is provided to demonstrate how to realize this.

Precautions

  • Signature calculation depends on open-source components crypto-js and js-base64, so an NPM module needs to be configured in the mini program.
  • During the mini program compilation, if error message "Maximum call stack size exceed" is reported when the crypto-js package is imported, upgrade the program to the latest version.
  • If 405 is returned during the upload, check whether the specified endpoint is the domain name of the bucket for storing uploaded files.

Procedure

  1. Enable CORS for a bucket.

    Mini programs are developed based on BrowerJS. Due to the same-origin policy, CORS rules must be configured if website scripts and content in one origin need to interact with those in another one. OBS supports CORS that allows resources to be accessed across origins. For detailed configurations, see Configuring CORS.

    The following table describes the suggestions on configuring CORS rules.

    Table 1 CORS rule parameters

    Parameter

    Description

    Recommended Configurations

    Allowed Origin

    Mandatory. It specifies the origin from which the requests can access the bucket.

    You can enter multiple origins, with one separated from another using a line break. Each origin can contain one wildcard character (*) at most. An example is as follows:

    http://rds.example.com
    https://*.vbs.example.com

    *

    Allowed Method

    Mandatory. It specifies the allowed cross-origin request methods, same as the operation types of buckets and objects. Request methods include Get, Post, Put, Delete, and Head.

    Select all of them.

    Allowed Header

    Optional. It specifies the allowed headers for cross-origin requests. Only CORS requests matching the allowed headers are valid.

    You can enter multiple allowed headers, with one separated from another using a line break. Each header can contain one wildcard character (*) at most. Spaces, ampersands (&), colons (:), and less-than signs (<) are not allowed.

    *

    Exposed Header

    Optional. It specifies the supplemented header in CORS responses, providing additional information for clients.

    You can enter multiple exposed headers, with one separated from another using a line break. Spaces, wildcard characters (*), ampersands (&), colons (:), and less-than signs (<) are not allowed.

    • ETag
    • x-obs-request-id
    • x-obs-api
    • Content-Type
    • Content-Length
    • Cache-Control
    • Content-Disposition
    • Content-Encoding
    • Content-Language
    • Expires
    • x-obs-id-2
    • x-reserved-indicator
    • x-obs-version-id
    • x-obs-copy-source-version-id
    • x-obs-storage-class
    • x-obs-delete-marker
    • x-obs-expiration
    • x-obs-website-redirect-location
    • x-obs-restore
    • x-obs-version
    • x-obs-object-type
    • x-obs-next-append-position

    Cache Duration (s)

    Mandatory. It specifies the duration (in seconds) that your browser can cache CORS responses. The default value is 100.

    Configure it based on your service needs.

  2. Add the bucket domain name to the whitelist of the mini program.

    Mini programs use a whitelist to manage cross-origin access. To implement data upload, you need to add the domain name for accessing the bucket to the whitelist of the mini program.

    1. Obtain the bucket's access domain name.

      In the bucket list, click the bucket you want to go to the Objects page. In the navigation pane, click Overview. In the Domain Name Details area, view the access domain name of the bucket.

      Figure 1 Viewing bucket's access domain name

    2. Set the bucket domain name to be valid in the server domain name configuration of the mini program.

  3. Calculate the POST upload signature.

    Before uploading a file using POST, calculate the signature based on the custom field policy. For details about signature calculation, see Authentication of Signature Carried in the Table Uploaded Through a Browser. The following provides the related source code.

    Base64 encoding on the policy (GetPolicy.js):

    const Base64 = require('js-base64');
    
    function getPolicyEncode(policy) {
      // Pass the policy field uploaded through a form and perform Base64 encoding on it.
      const encodedPolicy = Base64.encode(JSON.stringify(policy));
      return encodedPolicy;
    }
    
    module.exports = getPolicyEncode;

    Source code for calculating the signature (GetSignature.js):

    const Crypto = require('crypto-js');
    const Base64 = require('js-base64');
    
    function getSignature(policyEncoded, SecretKey){
      // Use the SK to perform HMAC-SHA1 signature calculation on the Base64-encoded policy.
      const bytes = Crypto.HmacSHA1(policyEncoded, SecretKey);
      // Perform Base64 encoding on the calculation result to obtain the final signature.
      const signature = Crypto.enc.Base64.stringify(bytes);
      return signature;
    }
    
    module.exports = getSignature;

  4. Use the mini program to transfer data to the OBS bucket.

    Based on the encoded policy and signature obtained in 3, call the upload API in the mini program to upload your local files. The sample code is as follows.

    Configuration file (Configuration.js) for configuring the AK, SK, and access domain name:

    • Use permanent access keys (AK/SK).
      // Specify the AK, SK, and endpoint for OBS.
      var Configuration = {
        // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables for identity authentication. Before running the code in this example, configure environment variables AccessKeyId and SecretKey.
        // The front-end code does not have the process environment variable, so you need to use a module bundler like webpack to define the process variable.
        // Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
        AccessKeyId: process.env.AccessKeyID,
        SecretKey: process.env.SecretAccessKey,
        EndPoint: 'https://your-test-bucket.obs.myhuaweicloud.com',         //Full bucket access domain name
      };
      
      
      module.exports = Configuration;
    • Use temporary access keys (AK/SK and security token).
      For details about how to obtain a temporary AK/SK pair and security token, see Obtaining a Temporary AK/SK Pair and Security Token.
      // Specify the AK, SK, security token, and endpoint for OBS.
      var Configuration = {
        // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables for identity authentication. Before running the code in this example, configure environment variables AccessKeyId and SecretKey.
        // The front-end code does not have the process environment variable, so you need to use a module bundler like webpack to define the process variable.
        // Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
        AccessKeyId: process.env.AccessKeyID,
        SecretKey: process.env.SecretAccessKey,
        SecurityToken: process.env.SecurityToken,        //securityToken
        EndPoint: 'https://your-test-bucket.obs.myhuaweicloud.com',         //Full bucket access domain name
      };
      
      
      module.exports = Configuration;

    The endpoint passed into the configuration file must be a full access domain name, for example, https://bucketName.obs.myhuaweicloud.com, where bucketName indicates the name of the bucket which the data is uploaded to through the mini program.

    // Import the configuration file.
    const config = require('./Configuration.js');
    // Import the calculation method for policy code.
    const getPolicyEncode = require('./getPolicy.js');
    // Import the signature calculation method.
    const getSignature = require('./GetSignature.js');
    
    const OBSupload = function (filePath){
      if(!filePath){
        wx.showToast({
          title: 'Invalid filePath',
          icon: 'Please re-select path',
        });
      }
      else{
        const fileName = 'testMiniprogram.jpg';   // Specify the name of the object to be uploaded to the bucket.
    
        const OBSPolicy = {                   // Configure the policy content. For details, see the hyperlink in Step 3.
          "expiration": "2021-12-31T12:00:00.000Z",
          "conditions": [
            { "bucket": "your-test-bucket"},  // Keep the bucket name same as that in the endpoint in the configuration file.
            // { "x-obs-security-token": config.SecurityToken } // This parameter is mandatory for authentication with temporary access keys.
            { 'key': fileName }
          ]
        }
    
        const policyEncoded = getPolicyEncode(OBSPolicy);                    // Calculate the Base64-encoded policy.
        const signature = getSignature(policyEncoded, config.SecretKey);     // Calculate the signature.
    
        wx.uploadFile({
          url: config.EndPoint,
          filePath: filePath,
          name: 'file',
          header: {
            'content-type': 'multipart/form-data; boundary=-9431149156168',
          },
          formData: {
            // Obtain the AK and encoded policy and signature from the configuration file.
            'AccessKeyID': config.AccessKeyId,
            'policy': policyEncoded,
            'signature': signature,
            'key': fileName,
            // "x-obs-security-token": config.SecurityToken, // This parameter is mandatory for authentication with temporary access keys.
          },
    
          success: function(res){
            console.log(res.statusCode);            //Print the response status code.
            if(res.statusCode=='204'){
              console.log('Uploaded successfully', res)
              wx.showToast({
                title: 'Uploaded successfully',
                icon: 'Success'
              });
            }
            else{
              console.log('Uploaded failed', res)
              wx.showToast({
                title: 'Uploaded failed',
                icon: 'Fail'
              });
            }
          },
          fail: function(e){
            console.log(e);
          }
        })
    
      }
    }
    
    module.exports = OBSupload;

Related Operations

After the upload is complete, obtain the URL for accessing the object. For details, see How Do I Obtain the Access Path to an Object?