Upload SDK for WeChat Mini Program
You can use the ApsaraVideo VOD Upload SDK to upload media files from a WeChat mini program to VOD storage.
Usage notes
The WeChat mini program SDK supports uploading audio, video, and image files. It does not support uploading auxiliary media assets.
Download SDK and demo
-
SDK version: 1.0.3
-
Update time: 2024-07-15
-
Package MD5 hash: 5145518e0bbb410c156b37c04c447a6f
-
Download address: WeChat mini program upload SDK and sample code
Integration SDK
Copy the SDK file to your project and import the dependency on the relevant page.
import VODUpload from 'aliyun-upload-sdk-1.0.3.min.js'
Basic settings
Initialize the upload instance
-
When you initialize the SDK instance, you must pass the userId parameter to identify the uploader. This parameter is required and cannot be empty. You can use your Alibaba Cloud account ID or a custom user ID. To view your account ID, go to the Account Center. If you do not pass the userId parameter or if you pass an empty value, an error is reported.
-
The
regionfield must be set to one of the region IDs supported by ApsaraVideo VOD.
var uploader = new VODUpload({
// The ID of your Alibaba Cloud account. This parameter cannot be empty. To view your account ID, go to the Account Center.
userId: "25346073170691****",
// The region where you want to upload files to ApsaraVideo VOD. Default value: 'cn-shanghai'. Other valid values include 'eu-central-1' and 'ap-southeast-1'. For more information, see Overview.
region: "cn-shanghai",
// The number of retries when an upload fails due to network issues. Default value: 3.
retryCount: 3,
// The interval between retries when an upload fails due to network issues. Default value: 2 seconds.
retryDuration: 2,
// The upload starts.
onUploadstarted: function (uploadInfo) {},
// The file is uploaded.
onUploadSucceed: function (uploadInfo) {},
// The file fails to be uploaded.
onUploadFailed: function (uploadInfo, code, message) {},
// The upload progress. Unit: bytes.
onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {},
// The upload credential expires.
onUploadTokenExpired: function (uploadInfo) {},
// All files are uploaded.
onUploadEnd: function (uploadInfo) {},
});
Set credentials
Review the overall client-side upload process and deploy the authorization service for your preferred method.
-
If you use the upload URL and credential method, you must obtain the upload URL and credential from the authorization service.
-
If you use the Security Token Service (STS) token method, you must obtain an STS token from the authorization service.
Set all authorization information in the onUploadstarted callback. When credentials expire, the onUploadTokenExpired callback is triggered. Call the appropriate method in this callback to refresh the credentials.
Upload URL and credential
Call the setUploadAuthAndAddress method. When the credential expires, the onUploadTokenExpired callback is triggered. Call the resumeUploadWithAuth method to set a new credential and resume the upload.
// The upload starts.
onUploadstarted: function (uploadInfo) {
console.log('Starting file upload...');
console.log("onUploadStarted:" + JSON.stringify(uploadInfo))
var url = "https://alivc-demo.aliyuncs.com/demo/getVideoUploadAuth?title=" + uploadInfo.url + "&fileName=" + uploadInfo.url + "&fileSize=" + uploadInfo.fileSize + "&description=description&coverURL=" + uploadInfo.coverUrl + "&tags=tags";
wx.request({
'url': url,
success: (res => {
if (res.statusCode === 200) {
var akInfo = res.data.data;
uploader.setUploadAuthAndAddress(uploadInfo, akInfo.uploadAuth, akInfo.uploadAddress, akInfo.imageId);
} else {
console.log(res)
uploader.stopUpload();
}
}),
fail: (res => {
uploader.stopUpload();
console.log(res)
})
});
},
// The upload credential expires.
onUploadTokenExpired: function (uploadInfo) {
const url = "https://alivc-demo.aliyuncs.com/demo/refreshVideoUploadAuth?videoId=" + uploadInfo.videoId;
wx.request({
'url': url,
success: (res => {
if (res.statusCode === 200) {
var akInfo = res.data.data;
uploader.resumeUploadWithAuth(akInfo.uploadAuth);
} else {
console.log(res)
uploader.stopUpload();
}
}),
fail: (res => {
uploader.stopUpload();
console.log(res)
})
});
},
Method description:
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
uploader.resumeUploadWithAuth(uploadAuth)
|
Parameter |
Description |
|
uploadInfo |
The first parameter of the onUploadstarted callback. |
|
uploadAuth |
The upload credential returned by the CreateUploadVideo operation. |
|
uploadAddress |
The upload URL returned by the CreateUploadVideo operation. |
|
videoId |
The audio or video ID returned by the CreateUploadVideo operation. |
STS token
Call the setSTSToken method. When the STS token expires, the onUploadTokenExpired callback is triggered. Call the resumeUploadWithSTSToken method to set a new STS token and resume the upload.
/* Callback method - The upload starts. */
onUploadstarted: function (uploadInfo) {
console.log('Starting file upload...');
console.log("onUploadStarted:" + JSON.stringify(uploadInfo))
wx.request({
url: "https://alivc-demo.aliyuncs.com/demo/getSts",
// data: data,
// header: header,
// method: method,
success: (res => {
if (res.statusCode === 200) {
var akInfo = res.data.data;
uploader.setSTSToken(uploadInfo, akInfo.accessKeyId, akInfo.accessKeySecret, akInfo.securityToken);
} else {
console.log(res)
}
}),
fail: (res => {
onError(res);
})
});
},
// The upload credential expires.
onUploadTokenExpired: function (uploadInfo) {
const url = "https://alivc-demo.aliyuncs.com/demo/getSts";
wx.request({
'url': url,
success: (res => {
if (res.statusCode === 200) {
var akInfo = res.data.data;
uploader.resumeUploadWithSTSToken(akInfo.uploadAuth);
} else {
console.log(res)
uploader.stopUpload();
}
}),
fail: (res => {
uploader.stopUpload();
console.log(res)
})
});
},
Method description:
uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken)
uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)
|
Parameter |
Description |
|
uploadInfo |
The first parameter of the onUploadstarted callback. |
|
accessKeyId |
The |
|
accessKeySecret |
The |
|
secretToken |
The |
Add files
<view class="weui-uploader__input-box">
<view class="weui-uploader__input" bindtap="chooseVideo"></view>
</view>// Select a video
chooseVideo: function (e) {
var that = this;
wx.chooseVideo({
sourceType: ['album', 'camera'],
maxDuration: 60,
compressed: false,
camera: 'back',
success: function (res) {
var file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
var uploader = that.data.uploader;
var paramData = '{"Vod":{}}';
uploader.addFile(file, null, null, null, paramData);
}
})
},
Method description:
uploader.addFile(file,endpoint,bucket,object,paramData)
|
Parameter |
Required |
Type |
Description |
|
file |
Yes |
File |
The file to upload. |
|
endpoint |
No |
String |
The OSS endpoint. If null, AppServer selects the endpoint. |
|
bucket |
No |
String |
The target bucket. If null, AppServer selects the bucket. |
|
object |
No |
String |
The target object. If null, AppServer selects the object. |
|
paramData |
No |
String |
File metadata such as title, description, transcoding, and callback settings. Specify The value of the |
Start the upload
uploader.startUpload();
-
After the file upload is started, the
onUploadProgresscallback is invoked to synchronize the upload progress. -
If the file upload is successful, the
onUploadSucceedcallback is invoked to return the upload result.
Advanced features
Use upload acceleration
To upload large files of gigabytes or terabytes, or upload videos across regions, such as from a region in the Chinese mainland to a storage address in the Singapore region, you can enable the upload acceleration feature.
To enable upload acceleration, submit a ticket. Provide your Account ID and the bucket to accelerate.
Method 1: Upload URL and credential
If you use this method to upload a file, call the CreateUploadVideo operation and specify key-value pairs in the UserData parameter to configure acceleration settings. Sample code:
UserData={
"AccelerateConfig": {
"Type": "oss",
"Domain": "https://oss-accelerate.aliyuncs.com"
}
}Method 2: STS token
If you use this method to upload a file, call the addFile method, add the UserData property to the parmData parameter, and then configure the upload content. Sample code:
uploader.addFile(file,null,null,null,'{"Vod":{"UserData":{"AccelerateConfig":{"Type":"oss","Domain":"https://oss-accelerate.aliyuncs.com"}}}}');UserData description
Name | Type | Required | Description |
userData | string | No | The custom configurations, such as callback configurations and upload acceleration configurations. The value must be a JSON string. |
The following table describes the parameters.
Parameter | Type | Description |
Type | string | The file type for which you want to enable upload acceleration. Set the value to oss. |
Domain | string | The accelerated domain name of the bucket. By default, HTTPS is used. Note An accelerated endpoint assigned after you enable upload acceleration is used, such as vod-*******.oss-accelerate.aliyuncs.com. |
For more information about how to configure UserData, see Request parameter descriptions.
Stop an upload
stopUpload takes effect only while a file is being uploaded.
uploader.stopUpload();
Manage a file list
Use the following operations to manage uploaded or in-progress files.
-
listFiles: Queries the upload list.
Returns files added via addFile. The file property indicates the file type. Traverse the list to get file indexes for management operations.
var list = uploader.listFiles(); for (var i=0; i<list.length; i++) { console.log("file:" + list[i].file.name); } -
deleteFile: Removes a file to be uploaded.
uploader.deleteFile(index);//The index of the file that you want to delete. The index is returned by the listFiles operation. -
cancelFile: Cancels the upload of a file.
Note-
After you call
cancelFile, theoss is cancel as errormessage appears in the console. This prevents uploaded parts from occupying storage and incurring costs. -
To resume a canceled upload, call
uploader.resumeFile(index);to restore the file first.
uploader.cancelFile(index); -
-
resumeFile: Resumes the upload of a file.
uploader.resumeFile(index); -
cleanList: Clears the upload list.
uploader.cleanList();
Troubleshooting
If an error occurs when you use the WeChat mini program SDK, identify the cause based on the error code. For more information, see Error codes.