Before you use the upload SDK for JavaScript to upload media files, you must integrate
the SDK. This topic describes how to integrate the upload SDK for JavaScript and use
the SDK to upload files.
Upload a file
Perform the following steps to upload a file by using the upload SDK for JavaScript:
- Import the upload SDK for JavaScript
For more information about how to download JavaScript scripts, see
SDK download. The upload SDK does not fully support modular loading. If you reference a file by
using the
import
or
require
method, the error
ReferenceError: OSS is not defined
is returned. Instead, you can use one of the following reference methods based on
your business requirements:
- Reference by using scripts in HTML. (Recommended)
<!-- The es6-promise file 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-sdk6.17.1.min.js"></script>
<script src="../aliyun-vod-upload-sdk1.5.2.min.js"></script>
- Reference by using a module.
You can manually assign the content in Object Storage Service (OSS) modules to Window.
The following code provides an example:
Note If a module is referenced by using a script in HTML, you do not need to manually reference
the module 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.2.min'
- Request an upload URL and an upload credential or a Security Token Service (STS) token for upload authorization.
If you use the upload SDK for JavaScript to upload a file, the process can be divided
to two steps: obtain an upload credential from the AppServer and upload the file to the OSS server. The latter is implemented by Alibaba Cloud. You need to only obtain the upload credential from the AppServer and specify the upload credential for the upload SDK for JavaScript. You can use
one of the following methods to obtain an upload credential:
Verify the resultUse 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.
This initialization process can be divided into two steps: declare an initialization
callback and initialize the upload instance.
- Declare an initialization callback.
Declare an
AliyunUpload.Vod
initialization callback. The following sample code describes the configurations that
you can specify:
var uploader = new AliyunUpload.Vod({
//Required. The ID of the account. You can log on to the Alibaba Cloud console and go to the Account Management page (https://account.console.aliyun.com/) to view your account ID.
userId:"122",
// The region to which you want to upload the file. Default value: cn-shanghai.
// eu-central-1, ap-southeast-1
region:"",
// The size of each part in multipart upload. Unit: byte. The default size is 1 MB (1024 × 1024). The size cannot be smaller than 100 KB (100 × 1024).
partSize: 1048576,
// The maximum number of parts that can be uploaded in parallel. Default value: 5.
parallel: 5,
// 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,
// This callback is fired when the upload starts.
'onUploadstarted': function (uploadInfo) {
},
// This callback is fired when the upload succeeds.
'onUploadSucceed': function (uploadInfo) {
},
// This callback is fired when the upload fails.
'onUploadFailed': function (uploadInfo, code, message) {
},
// This callback is fired when the default or custom upload progress is reached. The progress is measured in bytes.
'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
},
// This callback is fired when the upload credential or STS token expires.
'onUploadTokenExpired': function (uploadInfo) {
},
// This callback is fired when all files are uploaded.
'onUploadEnd':function(uploadInfo){
}
});
- Initialize the upload instance. Use an upload URL and an upload credential or an STS token to initialize the upload instance based on your business requirements.
In the onUploadstarted
callback, obtain an upload credential or refresh the upload credential. Select a
method to initialize the upload instance as needed.
- Use an upload URL and an upload 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 fired when the upload starts.
Notice When the upload credential (UploadAuth) expires, the onUploadTokenExpired
callback is fired. Call the resumeUploadWithAuth(uploadAuth)
method to resume the upload by using a new upload credential.
// Start the upload.
// The UploadInfo parameter contains the following information about the file to be uploaded:
// {
// videoId: '', // The ID of the video or audio file. The ID is returned by the AppServer.
// Endpoint: '', // The domain name that is used to access OSS.
// Bucket: '', // The OSS bucket.
// Object: ''// An object is the basic unit for data operations in OSS.
// }
'onUploadstarted': function (uploadInfo) {
// The upload method. You can call different operations of ApsaraVideo VOD to obtain values for the uploadauth and uploadAddress parameters based on whether the uploadInfo.videoId parameter is empty. The SDK obtains the value of the uploadInfo.videoId parameter from localstorage.
// If the videoId parameter has a value, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
// If you delete a video or audio file in the ApsaraVideo VOD console during the upload, the video ID no longer exists in the console but does exist in the browser. In this case, the error InvalidVideo.NotFound is returned. You must manually clear localstorage.
var url = '';
if (uploadInfo.videoId) {
// If the uploadInfo.videoId parameter has a value, call the RefreshUploadVideo operation.
url = 'refreshUrl'; // Specify the endpoint that is used to access the AppServer.
}
else{
// If the uploadInfo.videoId parameter does not have a value, call the CreateUploadVideo operation.
url = 'createUrl'; // Specify the endpoint that is used to access the AppServer.
}
// The following sample code provides an example on how to specify the upload credential:
// The required parameters vary based on the method called by the AppServer. You may need to set the UploadAuth, UploadAddress, and VideoId parameters.
fetch(url)
.then((res) => res.json())
.then((data) => {
uploader.setUploadAuthAndAddress(uploadInfo, data.UploadAuth, data.UploadAddress, data.VideoId);
});
},
// This callback is fired when the upload credential expires.
'onUploadTokenExpired': function (uploadInfo) {
// During implementation, call the RefreshUploadVideo operation to obtain a new value for the UploadAuth parameter based on the uploadInfo.videoId parameter.
// Specify the new value of the uploadAuth parameter obtained from ApsaraVideo VOD in the SDK.
var url = 'refreshUrl'; // Specify the endpoint that is used to access the AppServer.
// The following sample code provides an example on how to specify the upload credential:
// The required parameters vary based on the method called by the AppServer. You may need to set the UploadAuth, UploadAddress, and VideoId parameters.
fetch(url)
.then((res) => res.json())
.then((data) => {
uploader.resumeUploadWithAuth(data.UploadAuth);
});
},
- Use an 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 fired when the upload starts.
Notice When the STS token expires, the onUploadTokenExpired
callback is fired. Call the resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)
method to resume the upload by using a new STS token.
onUploadstarted: function (uploadInfo) {
// If you use an STS token to upload the file, you must call the uploader.setUploadAuthAndAddress method.
var stsUrl = 'stsUrl';
// The following sample code provides an example on how to specify the upload credential:
// The required parameters vary based on the method called by the AppServer. You may need to set the accessKeyId, accessKeySecret, and secretToken parameters.
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 you use an STS token to upload a file and the token expires during the upload, you can request a new STS token and resume the upload by using the new STS token.
// If the STS token is disabled during the upload because the uploaded file is too large, you must call the resumeUploadWithSTSToken method in the onUploadTokenExpired callback.
var stsUrl = 'stsUrl';
// The following sample code provides an example on how to specify the upload credential:
// The required parameters vary based on the method called by the AppServer. You may need to set the accessKeyId, accessKeySecret, and secretToken parameters.
fetch(stsUrl)
.then((res) => res.json())
.then((data) => {
var info = data.SecurityTokenInfo
uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
});
},
- Construct the upload parameters based on the type of the file to be uploaded.
- Select a file to be uploaded.
<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 audio or video file to be uploaded. |
endpoint |
No |
String |
The OSS endpoint. Specify the OSS endpoint based on the region to which you want to
upload the file. If you specify null, the actual value is determined by the AppServer.
|
bucket |
No |
String |
The bucket to which you want to upload the file. If you specify null, the actual value
is determined by the AppServer.
|
object |
No |
String |
The object to which you want to upload the file. If you specify null, the actual value
is determined by the AppServer.
|
paramsData |
No |
String |
If you use an STS token to upload the file, the paramData parameter can be used to configure audio information. The value of the paramData parameter is a JSON object in string format. In this JSON object, you must specify
the first Vod parameter. You can nest parameters that are supported by the paramData parameter under the Vod parameter. For more information, see CreateUploadVideo.
|
Sample code for the paramData parameter:
var paramData = '{"Vod":{"Title":"test","CateId":"234"}}';
Note You must specify the paramData parameter in the SDK only if you use the STS token
to upload a file. If you use an upload URL and an upload credential to upload a file,
you can specify the paramData parameter in the request of the CreateUploadVideo operation
rather than the SDK.
- Start the upload.
Note You can upload only a video or audio file from a client.
- Call the
startUpload()
method to start the upload.
- After the upload starts, the
onUploadProgress
callback is fired to synchronize the upload progress.
- If the file is uploaded, the
onUploadSucceed
callback is fired to return the upload result.
Execution result
- After a video is uploaded, the videoId parameter is returned. The value of the videoId
parameter indicates the video ID. Then, you must obtain a streaming URL to play the
video. For more information, see Use playback credentials to play videos.
- After an image is uploaded, the imageUrl parameter is not returned. You can Configure callbacks and set the ImageUploadComplete callback event in advance. After you receive the ImageUploadComplete callback event, you can obtain the URL of the image (FileURL) in the event notification.
The URL expires if you have enabled URL authentication. For more information, see
URL authentication.
Manage the upload list
You can call the following methods to manage files that are uploaded or being uploaded:
- Query the upload list
The returned upload list contains the information about the files that are added by
calling the addFile method. "file:" indicates that each element in the list is a file.
You can obtain the indexes of the files that you want to manage by traversing.
var list = uploader.listFiles();
for (var i=0; i<list.length; i++) {
log("file:" + list[i].file.name);
}
- Remove a file to be uploaded
uploader.deleteFile(index);// The index of the file to be removed. The index parameter indicates the index of an element returned by the listFiles() method.
- Cancel the upload of a single file
Note After the cancelFile
method is called, the oss is cancel as error
message is displayed in the console. This prevents the uploaded part files from occupying
storage space and saves unnecessary costs.
uploader.cancelFile(index);
- Resume the upload of a single file.
uploader.resumeFile(index);
- Clear the upload list.
uploader.cleanList();
Configure authorization settings
- Specify the upload URL and credential
Specify the upload URL and credential in the onUploadstarted
callback. The callback parameters include the uploadInfo
parameter.
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 of the onUploadstarted callback. |
uploadAuth |
The value can be obtained from the response of the CreateUploadVideo operation. |
uploadAddress |
The value can be obtained from the response of the CreateUploadVideo operation. |
videoId |
The value can be obtained from the response of the CreateUploadVideo operation. |
- Resume the upload after the upload credential expires
This method is called in the onUploadTokenExpired callback. You can specify a new
upload credential in this method when the credential expires. Set the uploadAuth parameter
to the new upload credential returned by the RefreshUploadVideo operation.
const {VideoId,UploadAuth,UploadAddress} = data;
uploader.resumeUploadWithAuth(UploadAuth);
- Specify the STS token
This method is called if you use an STS token to upload a file. Specify the STS token
in the onUploadstarted
callback. The callback parameters include the uploadInfo
parameter.
const {VideoId,UploadAuth,UploadAddress} = data;
uploader.setUploadAuthAndAddress(uploadInfo,UploadAuth,UploadAddress,VideoId);
Parameter |
Description |
uploadInfo |
The value can be obtained from the first parameter of the onUploadstarted callback. |
accessKeyId |
The value can be obtained from the response of the CreateSecurityToken operation. |
accessKeySecret |
The value can be obtained from the response of the CreateSecurityToken operation. |
secretToken |
The value can be obtained from the response of the CreateSecurityToken operation. |
- Resume the upload after the STS token expires
This method is called in the onUploadTokenExpired callback. You can specify a new
STS token in this method when the STS token expires.
var info = data.SecurityTokenInfo
uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
Upload management
Stop the upload
Note Make sure that a file is being uploaded when you call the stopUpload
method. Otherwise, the method does not work.
uploader.stopUpload();
Advanced features
Resumable uploadDuring the upload of a file, the upload may be interrupted due to the shutdown of
a page or the breakdown of the browser. In this case, if you upload the file again,
the SDK resumes the interrupted upload and obtains the upload credential from the
onUploadstarted
callback. If you use the upload URL and credential to upload the file, the value
of the videoId parameter that is returned in the callback can be used to query the
information about the breakpoint. The following sample code provides an example:
onUploadstarted': function (uploadInfo) {
if (Upload method 1) {
if(!uploadInfo.videoId)// No exception occurs when you upload the file.
{
// Call the CreateUploadVideo operation in your environment.
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
}
else// If the videoId parameter has a value, update the upload credential based on the value.
{
// Call the RefreshUploadVideo operation in your environment to update the upload credential.
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
}
}
else(Upload mode 2)
{
// Call the operation for obtaining 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);