Before you use the upload SDK for WeChat mini programs to upload files, you must integrate
the SDK. This topic shows you how to integrate the upload SDK for WeChat mini programs
and use the SDK to upload a file.
Upload a file
You can perform the following steps to upload a file by using the upload SDK for WeChat
mini programs:
- Import the JavaScript code.
- Request an upload URL and an upload credential or a Security Token Service (STS) token for upload authorization.
The upload SDK for WeChat mini programs supports the following two upload authorization
methods:
Verify the resultUse the obtained upload URL and credential or the obtained STS token to initialize
the upload instance.
- Use the upload URL and credential or the STS token to initialize an upload instance.
The initialization process consists of the following two steps:
- Declare a
VODUpload
initialization callback. var uploader = new VODUpload({
// The ID of your Alibaba Cloud account. This parameter cannot be left empty. To view the ID of your Alibaba Cloud account, go to the Account Management page (https://account.console.aliyun.com/) by using your Alibaba Cloud account.
userId:"25346073170691****",
// The ID of the region in which the file is to be uploaded. Default value: cn-shanghai. For more information about other region IDs such as eu-central-1 and ap-southeast-1, see Media asset storage.
region:"cn-shanghai",
// The maximum number of attempts to retry the upload upon a network exception. Default value: 3.
retryCount: 3,
// The intervals at which the system retries the upload upon a network exception. Default value: 2. Unit: seconds.
retryDuration: 2,
// The callback that is invoked if the upload starts.
'onUploadstarted': function (uploadInfo) {
},
// The callback that is invoked if the upload is successful.
'onUploadSucceed': function (uploadInfo) {
},
// The callback that is invoked if the upload fails.
'onUploadFailed': function (uploadInfo, code, message) {
},
// The callback that is invoked if the default or custom upload progress is reached. The progress is measured in terms of bytes.
'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
},
// The callback that is invoked if the upload credential or STS token expires.
'onUploadTokenExpired': function (uploadInfo) {
},
// The callback that is invoked if the entire file is uploaded.
'onUploadEnd':function(uploadInfo){
}
});
- Initialize the upload instance. Use the upload URL and credential or the STS token to initialize the upload instance as needed.
- Use the upload URL and credential (recommended)
Specify the obtained upload URL and credential in the SDK by calling the setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress,videoId);
method in the onUploadStarted
callback that is invoked when the upload starts.
Note If the upload credential expires, the onUploadTokenExpired
callback is invoked. Call the resumeUploadWithAuth(uploadAuth)
method to resume the upload by using a new upload credential.
// The callback that is invoked if the upload starts.
// The uploadInfo object specifies the information about the file that you want to upload.
// {
// videoId: '', // The video or audio ID that is returned by the server.
// Endpoint: '', // The Object Storage Service (OSS) endpoint for access from the Internet.
// Bucket: '', // The OSS bucket.
// Object: '' // The basic storage unit in OSS.
// }
'onUploadstarted': function (uploadInfo) {
// The upload method. You must call different methods to obtain the upload URL and credential, depending on whether the uploadInfo.videoId parameter has a value. The upload SDK obtains the value of the uploadInfo.videoId parameter from the local storage.
// If the uploadInfo.videoId parameter has a value, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
// If the video that is being uploaded is deleted from the ApsaraVideo VOD console, a conflict occurs. Specifically, the ApsaraVideo VOD console does not contain the video ID but the browser contains the video ID. In this case, the InvalidVideo.NotFound error message is reported. You must clear the local storage.
var url = '';
if (uploadInfo.videoId) {
// If the uploadInfo.videoId parameter has a value, call the RefreshUploadVideo operation.
url = 'refreshUrl'; // The endpoint of the application server.
}
else{
// If the uploadInfo.videoId parameter does not have a value, call the CreateUploadVideo operation.
url = 'createUrl'; // The endpoint of the application server.
}
// The following sample code shows how to specify the upload URL and credential in the upload SDK.
// The methods used to obtain the upload credential, upload URL, and video ID differ based on the application server.
fetch(url)
.then((res) => res.json())
.then((data) => {
uploader.setUploadAuthAndAddress(uploadInfo, data.UploadAuth, data.UploadAddress, data.VideoId);
});
},
// The callback that invoked if the upload credential expires.
'onUploadTokenExpired': function (uploadInfo) {
// During implementation, call the RefreshUploadVideo operation to obtain a new upload credential based on the uploadInfo.videoId parameter.
// Set the uploadAuth parameter to the new upload credential obtained from ApsaraVideo VOD in the SDK.
var url = 'refreshUrl'; // The endpoint of the application server.
// The following sample code shows how to resume the upload by using the new upload credential.
// The methods used to obtain the upload credential, upload URL, and video ID differ based on the application server.
fetch(url)
.then((res) => res.json())
.then((data) => {
uploader.resumeUploadWithAuth(data.UploadAuth);
});
},
- Use the STS token
Specify the obtained STS token in the SDK by calling the setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken);
method in the onUploadStarted
callback that is invoked when the upload starts.
Note If the STS token expires, the onUploadTokenExpired
callback is invoked. Call the resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)
method to resume the upload by using a new STS token.
onUploadstarted: function (uploadInfo) {
// If you use the STS token, call the uploader.setUploadAuthAndAddress method.
var stsUrl = 'stsUrl';
// The following sample code shows how to specify the STS token in the upload SDK.
// The methods used to obtain the AccessKey ID, AccessKey secret, and STS token differ based on the application server.
fetch(stsUrl)
.then((res) => res.json())
.then((data) => {
var info = data.SecurityTokenInfo
uploader.setSTSToken(uploadInfo, info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
});
},
onUploadTokenExpired: function (uploadInfo) {
// If the STS token expires, you must obtain a new STS token to resume the upload.
// If the file to be uploaded is large in size, the STS token may expire during the upload. In this case, you must call the resumeUploadWithSTSToken method in the onUploadTokenExpired callback to resume the upload by using a new STS token.
var stsUrl = 'stsUrl';
// The following sample code shows how to resume the upload by using the new STS token.
// The methods used to obtain the AccessKey ID, AccessKey secret, and STS token differ based on the application server.
fetch(stsUrl)
.then((res) => res.json())
.then((data) => {
var info = data.SecurityTokenInfo
uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
});
},
- Set upload parameters based on the type of the file that you want to upload. The file
can be an audio file, a video file, or an image file.
Upload parameters for audio and video filesSet the upload parameters for adding an audio or video file to the upload list.
wx.chooseVideo({
success: function (res) {
var file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
var userData = '{"Vod":{}}';
uploader.addFile(file, null, null, null, userData)
}
})
During the upload, you can use paramData
to customize audio and video information. paramData
is a JSON string. You must set Vod
at the first layer. Add attributes that paramData
supports withinVod
. For more information about supported attributes, see CreateUploadVideo. Sample code:
var userData = '{"Vod":{"Title":"test","CateId":"234"}"}';
Upload parameters for image filesSet the upload parameters for adding an image file to the upload list.
wx.chooseImage({
success: function (res) {
var file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
var userData = '{"Vod":{}}';
uploader.addFile(file, null, null, null, userData)
}
})
- Start the upload.
- Call the
startUpload()
method to start the upload.
- When the upload starts, invoke the
onUploadProgress
callback to synchronize the upload progress.
- If the file is uploaded, invoke the
onUploadSucceed
callback to return the upload result.
Upload result
- After a video is uploaded, the videoId parameter is returned, which indicates the
video ID. Then, you can obtain the streaming URL based on the video ID to play the
video. For more information, see Use playback credentials to play videos.
- After an image is uploaded, the imageUrl parameter is returned, which indicates the
image URL. If URL signing is enabled, the image URL expires after a specific period
of time. For more information, see URL authentication.
Manage the upload list
- Remove a file to be uploaded.
The index parameter indicates the index of a file in the list returned by the listFiles
method.
uploader.deleteFile(index);
- Cancel the upload of a single file.
uploader.cancelFile(index);
- Resume the upload of a single file.
uploader.resumeFile(index);
- Query the upload list.
uploader.listFiles();
- Clear the upload list.
uploader.cleanList();
Manage the upload credential or STS token
- Resume the upload after the upload credential expires.
uploader.resumeUploadWithAuth(uploadAuth);
- Specify the upload URL and credential.
Specify the upload URL and credential in the onUploadstarted
callback. The callback parameter is uploadInfo
.
uploader.setUploadAuthAndAddress(uploadInfo,uploadAuth, uploadAddress, videoId);
- Specify the STS token.
Specify the STS token in the onUploadstarted
callback. The callback parameter is uploadInfo
.
uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
- Resume the upload after the STS token expires.
uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
Control the upload
Stop the upload.
uploader.stopUpload();