This document explains how to use the ApsaraVideo VOD Upload SDK to upload videos from a WeChat mini program.
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
Version: 1.0.3
Release date: 2024-07-15
MD5 hash: 5145518e0bbb410c156b37c04c447a6f
Download link: SDK V1.0.3
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
First, understand the overall client-side upload process. Then, deploy the corresponding authorization service based on your preferred authorization 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.
All authorization information is set within the onUploadstarted callback. When credentials expire, the onUploadTokenExpired callback is triggered, where you must call the appropriate method to refresh the credentials.
Upload URL and credential
Call the setUploadAuthAndAddress method. When the credential expires, the onUploadTokenExpired callback is triggered. You can then 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 value can be obtained from the first parameter in 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
To set the STS token, call the setSTSToken method. When the STS token expires, the onUploadTokenExpired callback is triggered. You can then 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 value can be obtained from the first parameter in 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 video or audio file that you want to upload. |
endpoint | No | String | The OSS endpoint. If you set this parameter to null, the file is uploaded to an endpoint selected by AppServer. |
bucket | No | String | The bucket to which you want to upload the file. If you set this parameter to null, the file is uploaded to a bucket selected by AppServer. |
object | No | String | The object to which you want to upload the file. If you set this parameter to null, the file is uploaded to an object selected by AppServer. |
paramData | No | String | The information about the video or audio file that you want to upload, such as its title, description, transcoding settings, and callback settings. You can 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 activate the upload acceleration feature, submit a ticket. You need to provide your Account ID and the Bucket for which you want to enable upload acceleration.
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 parameters.
Stop an upload
You can call stopUpload only when a file is being uploaded. Otherwise, stopUpload does not take effect.
uploader.stopUpload();Manage a file list
You can call the following API operations to manage files that are uploaded or being uploaded. The following API operations are supported.
listFiles: Queries the upload list.
The returned data contains information about the files uploaded by calling the addFile method. The file property in the returned data indicates the file type. You can traverse the files to obtain the indexes of the files that you want to manage.
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.
NoteAfter you call
cancelFile, theoss is cancel as errormessage is displayed in the console. This prevents the uploaded parts from occupying storage space and generating storage costs.To resume a canceled an upload, you must use
uploader.resumeFile(index);to restore the file before you resume the upload.
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, use the error code to identify the cause. For more information, see Error codes.