This topic describes how to use the upload SDK for JavaScript to upload local media files to ApsaraVideo VOD.
Browser requirements
Browser | Supported | Version |
IE | ✔️ | Internet Explorer 10 and later |
Microsoft Edge | ✔️ | All |
Chrome | ✔️ | Mainstream browser versions |
Firefox | ✔️ | |
Safari | ✔️ | |
Android default browser | ✔️ | |
iOS default browser | ✔️ | |
Windows Phone default browser | ✔️ |
Feature description
You can use the upload SDK for JavaScript to upload only audio, video, and image files. You cannot use it to upload auxiliary media assets.
SDK and demo download
SDK version: 1.5.7.
Update time: January 30, 2024.
Download addresses: Upload SDK for JavaScript V1.5.7 and Demo source code of jQuery and Vue.
Integration methods
The upload SDK for JavaScript depends on Object Storage Service (OSS) SDK. You must specify a valid value for window.OSS. Otherwise, ReferenceError: OSS is not defined may be reported.
(Recommended) Import by using <script> in HTML code
<!-- es6-promise is required for Internet Explorer. Internet Explorer 10 and later are supported. -->
<script src="../lib/es6-promise.min.js"></script>
<script src="../lib/aliyun-oss-sdk-6.17.1.min.js"></script>
<script src="../aliyun-upload-sdk-1.5.7.min.js"></script>Import by using a module
You can manually specify the content of an OSS module as the value of window.OSS. Sample code:
If you already referenced files in HTML code by using <script>, you do not need to reference them again.
import OSS from '../lib/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min'
window.OSS = OSS;
import '../lib/aliyun-upload-sdk/aliyun-upload-sdk-1.5.7.min'Basic settings
Initialize the upload instance
When you initialize the SDK instance, you must specify the userId parameter to identify the uploader. The value can be an Alibaba Cloud account ID or a custom user ID. You can view the ID in Alibaba Cloud Account Center. If you do not specify the userId parameter or set this parameter to null, an error is reported.
You must specify the
regionparameter based on the region IDs supported by ApsaraVideo VOD. For more information, see Region IDs of ApsaraVideo VOD.
var uploader = new AliyunUpload.Vod({
// Required. The identity of the uploader. The value can be an Alibaba Cloud account ID or a custom user ID. You can view the ID in Alibaba Cloud Account Center (https://account-console.alibabacloud.com/).
userId: "122",
// The regions where you want to upload the files. Default value: cn-shanghai.
// Examples: eu-central-1 and ap-southeast-1.
region: "",
// The size of each part in a multipart upload. Unit: bytes. The size cannot be smaller than 100 KB (100 × 1024). Default size: 1 MB (1 × 1024 × 1024).
partSize: 1048576,
// The maximum number of parts that can be uploaded in parallel. Default value: 5.
parallel: 5,
// The maximum number of times the system retries the upload when a network error occurs. Default value: 3.
retryCount: 3,
// The interval at which the system retries the upload when a network error occurs. Default value: 2. Unit: seconds.
retryDuration: 2,
// The upload is started.
onUploadstarted: function (uploadInfo) {},
// The upload is successful.
onUploadSucceed: function (uploadInfo) {},
// The upload fails.
onUploadFailed: function (uploadInfo, code, message) {},
// The upload progress. Unit: bytes.
onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {},
// The upload credential or STS token expires.
onUploadTokenExpired: function (uploadInfo) {},
// All files are uploaded.
onUploadEnd: function (uploadInfo) {},
});
Configure the credential
Before you proceed, familiarize yourself with the overall upload process of a client and deploy an authorization service based on the corresponding authorization method. For more information, see Upload from clients.
If you use Method 1: Upload URL and credential, obtain an upload URL and credential from the authorization service. For more information, see Obtain upload URLs and credentials.
If you use Method 2: STS token, obtain an STS token from the authorization service. For more information, see Obtain an STS token.
You must configure the returned authorization information in the onUploadstarted callback. When the credential becomes invalid, the onUploadTokenExpired callback responds to the expiration. In this case, you must re-obtain a credential by calling the credential refresh operation.
Method 1: Upload URL and credential
To configure an upload URL and credential, call the setUploadAuthAndAddress method. If the credential expires, the system triggers the onUploadTokenExpired callback. In this case, you must call the resumeUploadWithAuth method to configure a new upload credential and resume the upload.
// The upload is started.
onUploadstarted: function (uploadInfo) {
let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
axios.get(refreshUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
let uploadAddress = data.UploadAddress
let videoId = data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
})
},
// The upload credential expires.
onUploadTokenExpired: function (uploadInfo) {
// If the upload of a large file times out when you use Method 1 (UploadAuth),
// call the RefreshUploadVideo operation based on uploadInfo.videoId and re-obtain the value of UploadAuth.
// Then, call the resumeUploadWithAuth method. In this example, the value of UploadAuth is directly obtained because resumeUploadWithAuth is a test method.
let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
axios.get(refreshUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
uploader.resumeUploadWithAuth(uploadAuth)
console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
})
self.statusText = 'The upload times out...'
},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. |
Method 2: STS token
To configure an STS token, call the setSTSToken method. If the token becomes invalid, the system triggers the onUploadTokenExpired callback. In this case, you must call the resumeUploadWithSTSToken method to configure a new STS Token and resume the upload.
/*Callback method - The upload is started.*/
onUploadstarted: function (uploadInfo) {
let stsUrl = "***.***.stsUrl" /*Use the setSTSToken method to obtain the STS token.*/
axios.get(stsUrl).then(({data}) => {
var info = data.SecurityTokenInfo
uploader.setSTSToken(uploadInfo, info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
})
},
/*Callback method - The credential times out.*/
onUploadTokenExpired: function (uploadInfo) {
let stsUrl = "***.***.stsUrl" /*Use the resumeUploadWithSTSToken method to refresh the STS token.*/
axios.get(stsUrl).then(({data}) => {
var info = data.SecurityTokenInfo
uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
})
},
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
Use the following code to listen to the change event in <input type="file" /> and add your files to the upload list of uploader.
Native JavaScript
<form action="">
<input type="file" name="file" id="files" multiple/>
</form>
<script>
userData = '';
document.getElementById("files")
.addEventListener('change', function (event) {
for(var i=0; i<event.target.files.length; i++) {
// The logic code.
uploader.addFile(event.target.files[i],null,null,null,null)
}
});
</script>
Vue
<template>
<input type="file" id="fileUpload" @change="fileChange($event)">
</template>
<script>
export default {
data () {
return {
file: null,
}
},
methods: {
fileChange (e) {
this.file = e.target.files[0]
if (!this.file) {
alert("Select the files that you want to upload.")
return
}
var Title = this.file.name
var userData = '{"Vod":{}}'
if (this.uploader) {
this.uploader.stopUpload()
}
// Initialize an uploader.
this.uploader = this.createUploader()
this.uploader.addFile(this.file, null, null, null, userData)
},
}
}
</script>
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.
Show the upload progress
// The file upload progress. Unit: bytes. You can use this function to obtain the upload progress and display the upload progress on the page.
onUploadProgress: function (uploadInfo, totalSize, progress) {
console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
let progressPercent = Math.ceil(progress * 100)
self.authProgress = progressPercent
self.statusText = 'The upload is ongoing...'
},Obtain the upload result
// The upload is successful.
onUploadSucceed: function (uploadInfo) {
console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
self.statusText = 'The upload is successful!'
},
// The upload fails.
onUploadFailed: function (uploadInfo, code, message) {
console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
self.statusText = 'The upload fails!'
},After a video is uploaded, you can use the videoId parameter to obtain the playback URL to play the video. For more information, see Obtain a playback credential.
imageUrlis not automatically returned when an image is uploaded. To obtain the image URL, you can configure a callback. For more information, see Configure callbacks.
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();
Perform a resumable upload
If an error occurs during a file upload, such as a forceful page shutdown or browser breakdown error, and you re-upload the file, the upload SDK for JavaScript resumes the upload from the breakpoint and obtains the upload credential from the onUploadstarted callback. If you use Method 1: Upload URL and credential to upload the file, you can call ApsaraVideo VOD API operations based on the value of the videoId parameter to obtain breakpoint information. Sample code:
// The upload is started.
onUploadstarted: function (uploadInfo) {
// If you use UploadAuth to upload the file, call the uploader.setUploadAuthAndAddress method.
// If you use UploadAuth to upload the file, call different ApsaraVideo VOD API operations to obtain uploadAuth and uploadAddress based on whether uploadInfo.videoId has a value.
// If uploadInfo.videoId has a value, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
// Take note of the following information: An operation is directly called to obtain UploadAuth because this is a test demo. In actual scenarios, you must call a specific operation to obtain UploadAuth based on whether uploadInfo.videoId has a value.
// If uploadInfo.videoId has a value, call the RefreshUploadVideo operation.
// If uploadInfo.videoId is empty, call the CreateUploadVideo operation.
if (!uploadInfo.videoId) {
let createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
axios.get(createUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
let uploadAddress = data.UploadAddress
let videoId = data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
})
self.statusText = 'The file upload is started...'
console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
} else {
// Display the breakpoint information.
console.log(uploader.getCheckpoint(uploadInfo.file));
// If the videoId parameter has a value, the video upload fails. The system resumes the upload from the breakpoint. You must refresh the upload credential based on the value of videoId.
let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
axios.get(refreshUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
let uploadAddress = data.UploadAddress
let videoId = data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
})
}
}You can use the following method to obtain the breakpoint information:
uploader.getCheckpoint(file);Exception handling
If an exception occurs when you use the upload SDK for JavaScript, you can refer to the error code to locate the cause. For more information, see the "Error codes supported by client upload SDKs" section of the Error codes topic.