Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Object Storage Service/ Best Practices/ Uploading Data to OBS/ Uploading Data from Mini Programs to OBS

Uploading Data from Mini Programs to OBS

Updated on 2024-10-17 GMT+08:00

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 of clients 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;
    NOTE:

    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?

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback