This topic describes how to integrate the upload SDK for JavaScript and use the SDK to upload local or online files from clients to ApsaraVideo VOD.
Prerequisites
The system settings required for the upload, including the storage path in the specified region and the callback settings, are configured. For more information, see Manage storage buckets and Configure callbacks.
A RAM user is created and used to access ApsaraVideo VOD. To prevent security risks caused by the leakage of the AccessKey pair of your Alibaba Cloud account, we recommend that you create a RAM user and grant the RAM user the permissions required to access ApsaraVideo VOD. Then, you can use the AccessKey pair of the RAM user to access ApsaraVideo VOD. For more information, see Create and grant permissions to a RAM user.
The upload SDK for JavaScript can be used in the following browsers:
Internet Explorer 10 and later
Edge
Major versions of Google Chrome, Firefox, or Safari
Major versions of the default browsers provided by Android, iOS, or Windows Phone
Download links: Upload SDK for JavaScript V1.5.6 and demo source code (jquery and Vue)
Upload processes
Client upload SDKs encapsulate the logic of uploading files to OSS buckets. When you upload medial files from clients, the files are directly uploaded to OSS buckets allocated by ApsaraVideo VOD without forwarding by servers. Therefore, the clients must be authenticated. You must deploy an authorization service on your application server to obtain upload URLs and credentials. Client upload SDKs support authorization based on upload credentials and authorization based on STS tokens. We recommend that you use an upload credential. For more information, see Comparison between credentials and STS.
Process of uploading a media file by using an upload URL and an upload credential
The following figure shows the complete process of uploading a media file by using an upload URL and an upload credential. In this example, ApsaraVideo VOD SDK is integrated to obtain the upload URL and credential.
A user deploys an authorization service on an application server, such as ApsaraVideo VOD SDK, to obtain upload URLs and credentials.
A client sends a request to the application server to request an upload URL and an upload credential.
The application server sends a request to ApsaraVideo VOD to request the upload URL and credential.
ApsaraVideo VOD returns the upload URL and credential.
NoteApsaraVideo VOD also generates media IDs, which can be used in media lifecycle management and media processing.
For a video, the media ID is returned in the
VideoId
parameter.For an image, the media ID is returned in the
ImageId
parameter.For an auxiliary media asset, the media ID is returned in the
MediaId
parameter.Properly keep the returned media IDs, which are required in subsequent tasks, such as media asset management, audio and video playback, and media processing.
The application server returns the upload URL and credential to the client.
NoteThe application server does not need to perform Base64 decoding on the upload URL or credential.
The client uses the upload URL and credential to initialize an upload instance.
The client constructs upload parameters to send an upload request.
OSS returns the upload result.
NoteYou can also set callbacks in advance to receive notifications about upload events.
Process of uploading a media file by using an STS token
If you use authorization based on the STS token, you must create a RAM role and grant the RAM role permissions to access ApsaraVideo VOD. For more information, see Use STS to upload videos.
The following figure shows the complete process of uploading a media file by using an STS token.
A user deploys an authorization service on an application server, such as ApsaraVideo VOD SDK, to obtain temporary STS tokens.
A client sends a request to the application server to request an STS token.
The application server sends a request to STS to request the STS token.
STS returns the token.
The application server returns the STS token to the client.
The client uses the STS token to initialize an upload instance.
The client constructs upload parameters to send an upload request.
OSS returns the upload result.
NoteYou can also set callbacks in advance to receive notifications about upload events.
Set the upload credential or STS token
This section describes how to set the upload credential for audio and video files. To obtain an image upload credential, call the CreateUploadImage operation.
Set the upload URL and credential
Set the upload URL and credential in the
onUploadstarted
callback.uploadInfo
is included in the callback.const {VideoId,UploadAuth,UploadAddress} = data; uploader.setUploadAuthAndAddress(uploadInfo,UploadAuth,UploadAddress,VideoId);
Parameter
Description
uploadInfo
The value can be obtained from the first parameter in the onUploadstarted callback.
uploadAuth
The value can be obtained from the response to the CreateUploadVideo operation.
uploadAddress
The value can be obtained from the response to the CreateUploadVideo operation.
videoId
The value can be obtained from the response to the CreateUploadVideo operation.
Resume the upload after the upload credential expires
Call the resumeUploadWithAuth operation in the onUploadTokenExpired callback to resume the upload after the upload credential expires. Set uploadAuth to the new upload credential returned in the response to the RefreshUploadVideo operation.
const {VideoId,UploadAuth,UploadAddress} = data; uploader.resumeUploadWithAuth(UploadAuth);
Set the STS token
Call setSTSToken to set the STS token for file upload. Call setSTSToken in the
onUploadstarted
callback.uploadInfo
is included in the callback.var info = data.SecurityTokenInfo uploader.setSTSToken(uploadInfo,info.AccessKeyId,info.AccessKeySecret,info.SecretToken);
Parameter
Description
uploadInfo
The value can be obtained from the first parameter in the onUploadstarted callback.
accessKeyId
The value can be obtained from the response to the CreateSecurityToken operation.
accessKeySecret
The value can be obtained from the response to the CreateSecurityToken operation.
secretToken
The value can be obtained from the response to the CreateSecurityToken operation.
Resume the upload after the STS token expires
Call resumeUploadWithSTSToken in the onUploadTokenExpired callback to update the upload credential after it expires.
var info = data.SecurityTokenInfo uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
Upload a file
Perform the steps described in this section to upload a file by using the upload SDK for JavaScript.
If the upload on the web client is interrupted, a 404 error may occur when you try to re-upload the file. You can update the upload SDK to V1.5.3 or later and re-upload the file. If you use the upload SDK for JavaScript that is earlier than V1.5.3, rename the file before you re-upload the file to prevent errors.
If you want to upload multiple files at the same time, you can create multiple upload instances. Each upload instance represents an upload task for a single file. You cannot use an upload instance to upload multiple files at the same time.
Integrate the upload SDK for JavaScript.
Download the upload SDK for JavaScript package. For more information, see SDK overview and download. The upload SDK provides only partial support for external modules. If you call the
import
orrequire
method to reference files, theReferenceError: OSS is not defined
error message is returned. You can use one of the following methods to reference files based on your business requirements:(Recommended) Reference by using scripts in HTML
<!-- The es6-promise file is required for Internet Explorer. Internet Explorer 10 and later versions 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.5.min.js"></script>
Reference by using a module
You can manually add an Object Storage Service (OSS) module to the window. Sample code:
NoteIf you have already referenced files on the HTML page by using scripts, you do not need to add the module.
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.5.min'
Obtain an upload URL and an upload credential or an STS token for upload authorization.
If you use the upload SDK for JavaScript to upload a file, you must obtain an upload credential from AppServer and upload the file to the OSS server on Alibaba Cloud. After you obtain the upload credential from AppServer, specify the credential in the configurations of the SDK. You can use one of the following methods to obtain an upload credential:
For more information about how to obtain the upload URL and credential, see Obtain upload URLs and credentials.
For more information about how to obtain an STS token, see Obtain an STS token.
Upload result
Use the obtained upload URL and credential or the obtained STS token to initialize the upload instance.
Initialize the upload instance by using an upload credential or an STS token. We recommend that you use an upload credential to initialize the upload instance.
You need to configure the initialization callback before you initialize the upload instance.
Configure the initialization callback.
Configure a callback for
AliyunUpload.Vod
. The following sample code provides an example of the configurations that you can specify when you initialize the upload instance:NoteFor more information about the supported regions of ApsaraVideo VOD and the corresponding endpoints, see Region IDs of ApsaraVideo VOD.
Initialize an upload instance. You can use an upload URL and an upload credential or an STS token to initialize the upload instance based on your business requirements.
Obtain or update the upload credential in the
onUploadstarted
callback. Use one of the following methods to initialize the upload instance based on your business requirements:(Recommended) Use an upload URL and an upload credential
Specify the upload URL and credential by calling the
setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress,videoId)
method in theonUploadStarted
callback that is fired when the upload starts.Sample code for uploading an audio or video file
NoteThe
onUploadTokenExpired
callback is fired when the upload credential expires. Call theresumeUploadWithAuth(uploadAuth)
method to set a new credential and resume the upload.Sample code for uploading an image
NoteThe upload credential is not automatically updated when you upload an image. After the upload credential expires, the ImageId becomes invalid and can be deleted. In this case, you must obtain a new credential to upload the image.
Use an STS token
Specify the obtained STS token by calling the
setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken);
method in theonUploadStarted
callback that is fired when the upload starts.NoteThe
onUploadTokenExpired
callback is fired when the STS token expires. Call theresumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)
method to set a new STS token and resume the upload.
Configure the parameters for the upload based on the type of the file that you want to upload.
Select a file that you want to upload.
<form action=""> <input type="file" name="file" id="files" multiple/> </form> userData = ''; document.getElementById("files") .addEventListener('change', function (event) { for(var i=0; i<event.target.files.length; i++) { // The logic code. } });
Add the selected file to the upload list.
uploader.addFile(file,null,null,null,'{"Vod":{}}');
Parameter
Required
Type
Description
file
Yes
File
The video or audio file that you want to upload.
endpoint
No
String
The OSS endpoint. Specify the OSS endpoint based on the region in which you want to upload the file. If you specify 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 specify 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 specify null, the actual value is determined by AppServer.
paramData
No
String
The information about the video or audio file that you want to upload such as the title and description of the video or audio file and transcoding and callback settings for the video or audio file. You can specify
paramData
if you use an STS token to upload a video or audio file to ApsaraVideo VOD.The value of
paramData
is a JSON string. You must specifyVod
in the request. You can nest parameters that are supported by theparamData
parameter underVod
. For more information, see CreateUploadVideo or CreateUploadImage.Sample code:
NoteYou must specify paramData for the SDK only if you use an STS token to upload a file. If you use an upload URL and an upload credential to upload a file, specify paramData only when you call the CreateUploadVideo or CreateUploadImage operation.
If you specify both the WorkflowId and TemplateGroupId, the value of the WorkflowId parameter takes effect.
Specify the title and category ID of the video or audio file.
var paramData = '{"Vod":{"Title":"test","CateId":"234"}}';
Specify the title of the video or audio file and the ID of the transcoding template group.
var paramData = '{"Vod":{"Title":"test","TemplateGroupId":"e6bb587b5365ac38a41462a4940****"}}';
Specify the title of the video or audio file and the ID of the workflow.
var paramData = '{"Vod":{"Title":"test","WorkflowId":"e2d027f16b5ee9cdf126266d32d****"}}';
Start the upload.
Call the
startUpload()
method to start the upload.uploader.startUpload();
Fire the
onUploadProgress
callback to synchronize the upload progress when the upload starts.Fire the
onUploadSucceed
callback to return the upload result when the file is uploaded.
Upload result
After a video or audio file is uploaded, videoId is returned. Then, you need to obtain a playback URL to play the file. For more information, see Use playback credentials to play videos.
imageUrl is not automatically returned when an image is uploaded. To obtain the image URL, configure a callback for the ImageUploadComplete event before you upload images. You can obtain the FileURL in the ImageUploadComplete callback. For more information, see Configure callbacks. If you have enabled URL signing, the URL expires after the validity period elapses. For more information, see Configure URL signing.
Advanced features
Upload management
Stop the upload
You can call stopUpload
only when a file is being uploaded. Otherwise, the API operation does not take effect.
uploader.stopUpload();
Queue management
You can call the following API operations to manage files that are uploaded or being uploaded. The following section describes the API operations that are supported.
listFiles
The returned data contains information about the files that are uploaded by calling addFile. The file property in the returned data indicates the file type. You can traverse the list to obtain the indexes of the files that you want to manage.
var list = uploader.listFiles(); for (var i=0; i<list.length; i++) { log("file:" + list[i].file.name); }
deleteFile
uploader.deleteFile(index);// The index of the file that you want to delete. The index is returned by the listFiles operation.
cancelFile
NoteAfter
cancelFile
is called, theoss is cancel as error
message is displayed in the console. This prevents the uploaded parts from occupying the storage space and reduces storage costs.If you want to resume the upload after you cancel a upload, you must use
uploader.resumeFile(index);
to restore the file before you resume the upload.
uploader.cancelFile(index);
resumeFile
uploader.resumeFile(index);
cleanList
uploader.cleanList();
Resumable upload
If errors such as forceful page shutdown and browser breakdown occur during file upload and you try to 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 the upload URL and credential to upload the file, call API operations in ApsaraVideo VOD to obtain breakpoint information based on the value of videoId. Sample code:
onUploadstarted: function (uploadInfo) {
if (Upload method 1) {
if(!uploadInfo.videoId)// No error occurred during file upload.
{
// Call the CreateUploadVideo operation in your environment.
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
}
else// If the videoId parameter is not empty, update the upload credential based on the value of videoId.
{
// Call the RefreshUploadVideo operation in your environment to update the upload credential.
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
}
}
else(Upload method 2)
{
// Call the setSTSToken operation to obtain the STS token in your environment.
uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
}
}
You can call the following method to obtain the breakpoint information:
uploader.getCheckpoint(file);