Upload files directly from an Alipay mini program
This topic describes how to upload files to Object Storage Service (OSS) from an Alipay mini program.
Background information
Mini programs, such as WeChat mini programs and Alipay mini programs, are popular mobile applications. They are a type of application that does not require download or installation, which provides a better experience for end users. Uploading files to OSS from a mini program environment is a common requirement for developers.
Similar to direct uploads from a JavaScript client, you can upload files from a mini program to OSS. This is accomplished using the PostObject operation to upload files through a form. For more information about PostObject, see PostObject.
Step 1: Obtain a signature
To ensure data security, upload files using a signature. OSS provides code for two signature methods:
Server-side signature
When you use a server-side signature, you must first build a signature service. The client then calls the signature service to generate the signature.
Server-side signature source code
The following code is the uploadOssHelper.js file:
const crypto = require("crypto-js"); class MpUploadOssHelper { constructor(options) { this.accessKeyId = options.accessKeyId; this.accessKeySecret = options.accessKeySecret; this.timeOut = options.timeout || 1; // The validity period of the parameters in hours. this.maxSize = options.maxSize || 10; // The maximum size of the file to upload in MB. } createUploadParams() { const policy = this.getPolicyBase64(); const signature = this.signature(policy); return { OSSAccessKeyId: this.accessKeyId, policy: policy, signature: signature, }; } getPolicyBase64() { let date = new Date(); // Set the expiration time of the policy. date.setHours(date.getHours() + this.timeOut); let srcT = date.toISOString(); const policyText = { expiration: srcT, conditions: [ // Limit the size of the file to upload. ["content-length-range", 0, this.maxSize * 1024 * 1024], ], }; const buffer = new Buffer(JSON.stringify(policyText)); return buffer.toString("base64"); } signature(policy) { return crypto.enc.Base64.stringify( crypto.HmacSHA1(policy, this.accessKeySecret) ); } } module.exports = MpUploadOssHelper;Server-side API example
The following code provides an example of an API that uses Express:
const express = require('express'); const app = express(); const MpUploadOssHelper = require("./uploadOssHelper.js"); app.get('/getPostObjectParams', (req, res) => { const mpHelper = new MpUploadOssHelper({ // Enter the AccessKey ID. accessKeyId: '<Your AccessKeyId>', // Enter the AccessKey secret. accessKeySecret: '<Your AccessKeySecret>', // The validity period of the parameters in hours. timeout: 1, // The maximum size of the file to upload in MB. maxSize: 10, }); // Generate parameters. const params = mpHelper.createUploadParams(); res.json(params); })
Client-side signature
When you use a client-side signature, you must first build a Security Token Service (STS) on the server. The client then obtains a temporary STS credential and generates a signature.
Build an STS service on the server
const OSS = require('ali-oss') const STS = OSS.STS const express = require('express'); const app = express(); const stsClient = new STS({ // Enter your AccessKey ID. accessKeyId: '<Your AccessKeyId>', // Enter your AccessKey secret. accessKeySecret: '<Your AccessKeySecret>', // Enter the bucket name. bucket: '<Your bucket name>' }); async function getToken() { // Specify the Amazon Resource Name (ARN) of the role. Format: acs:ram::$accountID:role/$roleName. const STS_ROLE = '<STS_ROLE>' const STSpolicy = { Statement: [ { Action: ['oss:*'], Effect: 'Allow', Resource: ['acs:oss:*:*:*'] } ], Version: '1' }; const result = await stsClient.assumeRole( // Enter the ARN of the RAM role used for authorization. For more information, see View RAM roles. STS_ROLE, STSpolicy, // Specify the expiration time of the STS token in seconds. 3600 ); const { credentials } = result; return credentials; } app.get('/getToken', async (req, res) => { // Obtain the STS token. const credentials = await getToken() console.log(credentials.AccessKeyId) console.log(credentials.AccessKeySecret) console.log(credentials.SecurityToken) res.json(credentials); })Obtain a temporary STS credential and generate a signature on the client
import crypto from 'crypto-js'; import { Base64 } from 'js-base64'; import axios from 'axios'; // Calculate the signature. function computeSignature(accessKeySecret, canonicalString) { return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret)); } const date = new Date(); date.setHours(date.getHours() + 1); const policyText = { // Set the expiration time of the policy. expiration: date.toISOString(), conditions: [ // Limit the size of the file to upload. ["content-length-range", 0, 1024 * 1024 * 1024], ], }; async function getFormDataParams() { const credentials = await axios.get('/getToken') const policy = Base64.encode(JSON.stringify(policyText)) // The policy must be a Base64-encoded string. const signature = computeSignature(credentials.AccessKeySecret, policy) const formData = { OSSAccessKeyId: credentials.AccessKeyId, signature, policy, 'x-oss-security-token': credentials.SecurityToken } return formData }
Step 2: Upload a file from an Alipay mini program
The following sample code demonstrates how to upload a file from an Alipay mini program:
const host = '<host>';
const signature = '<signatureString>';
const ossAccessKeyId = '<accessKey>';
const policy = '<policyBase64Str>';
const securityToken = '<x-oss-security-token>';
const key = '<object name>'
my.chooseImage({
chooseImage: 1,
success: res => {
const path = res.apFilePaths[0];
my.uploadFile({
url: host,
fileType: 'image',
fileName: 'file',
filePath: path,
formData: {
key,
policy,
OSSAccessKeyId: ossAccessKeyId,
signature,
success_action_status: '200',
// If you use an STS signature, pass the securityToken.
// 'x-oss-security-token': securityToken
},
success: (res) => {
// Set the status code for a successful upload to 200. The default status code is 204.
if (res.statusCode === 200) {
console.log('Upload successful');
}
my.alert({ content: 'success info: ' + res.data });
},
fail: err => {
console.log(err);
}
});
}
});The parameters are described as follows:
host: The endpoint of the bucket. For example, https://test.oss-cn-zhangjiakou.aliyuncs.com. If you have attached a custom domain name to the bucket, use the custom domain name.
signature: The signature that you obtained in Step 1.
ossAccessKeyId: Your AccessKey ID. If you use a temporary credential obtained from STS, specify the AccessKey ID of the temporary user.
policy: The policy information that you obtained in Step 1.
key: The path of the file after it is uploaded to OSS. For example, to upload myphoto.jpg to the test folder, set this parameter to test/myphoto.jpg.
securityToken: If you use STS for authentication, set this parameter to the SecurityToken obtained during client-side signing.