Upload files using the JavaScript SDK
This topic describes how to use the JavaScript SDK to upload media files from your local machine to ApsaraVideo VOD storage.
Browser requirements
Browser | Version |
Chrome | 66+ |
Microsoft Edge | 79+ (Chromium-based) |
Firefox | 57+ |
Safari | 12.1+ |
Default Android browser | 66+ |
Default iOS browser | 12.2+ |
Demo download
Download URL: Demo source code
Quick integration
Installation
npm install aliyun-vod-upload-sdkThe SDK ships three build artifacts — ESM, CJS, and UMD — and supports all modern bundlers (Vite, webpack, Rollup, and esbuild).
CDN import
<script src="https://g.alicdn.com/apsara-media-box/imp-web-vod-upload/2.1.0/vod-upload.umd.js"></script>
<script>
const { createUploader, UploadError } = window.AliyunVodUpload;
</script>Upload in five lines of code
import { createUploader } from 'aliyun-vod-upload-sdk';
const uploader = createUploader({
getAuth: () => fetch('/api/vod/auth').then(r => r.json()),
});
const { videoId } = await uploader.upload(file);Backend API requirements
In getAuth mode, the SDK does not call Alibaba Cloud OpenAPI directly. Instead, it delegates upload credential retrieval to your backend through the getAuth callback. Your backend must implement the following APIs (mapped to VOD OpenAPI operations):
Backend API | Corresponding OpenAPI operation | Response fields |
Create a video upload credential | CreateUploadVideo |
|
Refresh a video upload credential | RefreshUploadVideo |
|
Create an image upload credential | CreateUploadImage |
|
Create an auxiliary media asset upload credential | CreateUploadAttachedMedia |
|
Pass the JSON returned by your backend to the SDK as is. The SDK automatically performs Base64 decoding and field mapping internally.
If your server can provide only STS temporary credentials, use the getSTS direct upload mode: the SDK signs and calls the preceding VOD OpenAPI operations directly in the browser, so you do not need to implement these APIs.
Basic features
Upload videos
import { createUploader } from 'aliyun-vod-upload-sdk';
const uploader = createUploader({
getAuth: async (ctx) => {
switch (ctx.kind) {
case 'create-video':
return fetch('/api/vod/create-auth', {
method: 'POST',
body: JSON.stringify({ fileName: ctx.file.name, ...ctx.meta }),
}).then(r => r.json());
case 'refresh-video':
return fetch(`/api/vod/refresh-auth?videoId=${ctx.videoId}`)
.then(r => r.json());
}
},
});
const result = await uploader.upload(file, {
meta: { title: 'My video', cateId: 1000, tags: 'tutorial,example' },
});
console.log('Upload succeeded, videoId:', result.videoId);getAuth callback receives a single ctx parameter, and the SDK automatically determines ctx.kind based on the scenario:
create-video— the first upload. Your backend must call CreateUploadVideo.refresh-video— a credential refresh during a resumable upload or after the credential expires. Your backend must call RefreshUploadVideo.create-image— an image upload. Your backend must call CreateUploadImage.create-attached-media— an auxiliary media asset upload. Your backend must call CreateUploadAttachedMedia.
Upload images
Image uploads use the same upload() method. The SDK detects the file type automatically from file.type (the image/* type goes through the image pipeline):
const uploader = createUploader({
getAuth: async (ctx) => {
if (ctx.kind === 'create-image') {
return fetch('/api/vod/image-auth', {
method: 'POST',
body: JSON.stringify({ imageType: 'default' }),
}).then(r => r.json());
}
},
});
const result = await uploader.upload(imageFile);
console.log('Image upload succeeded, imageId:', result.imageId);Upload auxiliary media assets (watermarks / subtitles / materials)
Watermark images, subtitle files (srt / ass / vtt), and materials (zip / image / video clip) require CreateUploadAttachedMedia - Obtain the upload URL and credential of an auxiliary media asset. In meta, include businessType to route the upload to this pipeline. Everything else works exactly as it does for videos and images (progress, cancellation, timeout retry, and event tracking).
// Subtitle: without businessType, an .srt file is taken over by the video pipeline and creates a video record with the wrong type
const r1 = await uploader.upload(srtFile, { meta: { businessType: 'subtitle' } });
// Material
const r2 = await uploader.upload(materialFile, { meta: { businessType: 'material' } });
// Watermark image: goes through the auxiliary media asset pipeline (its output is a different resource type from "image pipeline + imageType: 'watermark'")
const r3 = await uploader.upload(logoFile, {
meta: { businessType: 'watermark', mediaExt: 'png' },
});
console.log('mediaId:', r1.mediaId); // Unified field across the three pipelines: video = VideoId, image = ImageId, auxiliary media asset = MediaIdbusinessType / mediaExt and related fields are described below:
Field | Description |
| Required. The value is passed through to VOD as is (documented values: |
| Optional. When it is omitted, STS mode derives it from the file name extension ( |
| Optional. These fields are equivalent to the video |
Two behavioral differences:
No resumable upload: ApsaraVideo VOD has no Refresh version of this API (the credential is valid for about 3,000 seconds, and after it expires you can only call Create again and receive a new
MediaId), so the SDK does not read or write checkpoints for auxiliary media assets. Re-uploading after an interruption is a brand-new upload.PNG watermarks have two official paths: the image pipeline (
VodImageMeta.imageType = 'watermark') and the auxiliary media asset pipeline (businessType: 'watermark') produce two different types of resources. The SDK does not decide for you: only when you passbusinessTypedoes the upload go to the auxiliary media asset pipeline. Without it, the upload follows the image pipeline based on the file type.
In uploadAuth mode, getAuth receives ctx.kind === 'create-attached-media'. Pass ctx.meta.businessType to your backend. In STS mode (getSTS), the SDK signs and calls the API automatically, and getSTS requires no changes.
Upload progress
const result = await uploader.upload(file, {
onProgress: (percent, loaded, total) => {
// percent: 0..1 (for example, 0.5 means 50%)
// loaded: bytes uploaded so far
// total: total file size in bytes
progressBar.value = percent;
console.log(`${(percent * 100).toFixed(1)}% - ${loaded} / ${total}`);
},
});The SDK guarantees that when an upload completes, percent eventually equals 1.
Cancel an upload
Option 1: task.abort() — the simplest approach
const task = uploader.upload(file); cancelBtn.onclick = () => task.abort(); try { const result = await task; } catch (e) { if (e.name === 'AbortError') { console.log('The user canceled the upload'); } }Option 2: AbortSignal — best suited to React and Vue component lifecycles
const ctrl = new AbortController(); cancelBtn.onclick = () => ctrl.abort(); try { const result = await uploader.upload(file, { signal: ctrl.signal }); } catch (e) { if (e.name === 'AbortError') { console.log('Canceled'); } }
After a cancellation the checkpoint is retained, so the next upload(file) call automatically resumes from the checkpoint (videos only; images and auxiliary media assets do not use resumable upload, and uploading them again starts a brand-new upload).
Resumable upload
Resumable upload is enabled by default and requires no extra configuration (video uploads only; image and auxiliary media asset uploads do not use resumable upload). The SDK automatically:
Stores the progress of completed parts in
localStorage.After the page refreshes, call
upload(file)again, and the upload automatically continues from where it stopped.Matching rule: the same file.name + file.size + file.lastModified hits the checkpoint.
// First upload (the user closes the page when 40% is uploaded)
await uploader.upload(file);
// The user reopens the page and uploads the same file again
// SDK automatically resumes from 40% and does not upload the data again
const result = await uploader.upload(file);Disable resumable upload:
const uploader = createUploader({
getAuth: myGetAuth,
checkpoint: false, // disabled
});Advanced features
Batch upload
The SDK provides a single-file upload() API. Compose standard JavaScript asynchronous primitives for batch uploads:
// Sequential upload (the simplest approach)
for (const file of files) {
const result = await uploader.upload(file, {
onProgress: p => updateProgress(file.name, p),
});
console.log(`${file.name} completed, videoId: ${result.videoId}`);
}// Concurrent upload (high bandwidth + small files)
const results = await Promise.all(
files.map(f => uploader.upload(f)),
);// Limited concurrency (recommended for large files)
import pLimit from 'p-limit';
const limit = pLimit(2); // upload at most 2 files at the same time
const results = await Promise.all(
files.map(f => limit(() => uploader.upload(f, {
onProgress: p => updateItemProgress(f, p),
}))),
);Pause and resume
The SDK has no explicit pause API. You achieve pausing through cancel + resume:
// Pause: cancel the current upload
task.abort();
// Resume: upload the same file again; it automatically resumes from the checkpoint
const result = await uploader.upload(file);Timeout cancellation and multi-source cancellation
// 60 second timeout with automatic cancellation
await uploader.upload(file, {
signal: AbortSignal.timeout(60_000),
});
// Multi-source cancellation: the user cancels manually, or a 60-second timeout occurs
const userCtrl = new AbortController();
await uploader.upload(file, {
signal: AbortSignal.any([
userCtrl.signal,
AbortSignal.timeout(60_000),
]),
});AbortSignal.timeout requires Chrome 103+, and AbortSignal.any requires Chrome 116+. The SDK itself is compatible down to Chrome 60. To support older browsers, use the AbortController+setTimeout combination.
React and Vue integration
React Hook example
import { useEffect, useRef, useState } from 'react';
import { createUploader } from 'aliyun-vod-upload-sdk';
function useUploader(getAuth) {
const uploaderRef = useRef(null);
// Create it inside the effect to avoid calling createUploader on every render;
// StrictMode causes the effect to run, clean up, and run again; the instance disposed during cleanup is recreated
useEffect(() => {
const uploader = createUploader({ getAuth });
uploaderRef.current = uploader;
return () => {
uploader.dispose(); // Release resources on unmount and cancel in-progress uploads
uploaderRef.current = null;
};
}, []);
return uploaderRef;
}
function UploadButton({ file }) {
const uploaderRef = useUploader(myGetAuth);
const ctrlRef = useRef(null);
const [progress, setProgress] = useState(0);
const handleUpload = () => {
const uploader = uploaderRef.current;
if (!uploader) return;
const ctrl = new AbortController();
ctrlRef.current = ctrl;
uploader.upload(file, {
signal: ctrl.signal,
onProgress: p => setProgress(p),
}).then(result => {
console.log('Succeeded', result.videoId);
}).catch(e => {
if (e.name !== 'AbortError') {
console.error('Failed', e);
}
});
};
return (
<>
<button onClick={handleUpload}>Upload ({(progress * 100).toFixed(0)}%)</button>
<button onClick={() => ctrlRef.current?.abort()}>Cancel</button>
</>
);
}Vue 3 Composable example
import { onUnmounted, ref } from 'vue';
import { createUploader } from 'aliyun-vod-upload-sdk';
export function useUploader(getAuth) {
const uploader = createUploader({ getAuth });
const progress = ref(0);
onUnmounted(() => uploader.dispose());
async function upload(file) {
return uploader.upload(file, {
onProgress: p => { progress.value = p; },
});
}
return { upload, progress };
}API reference
createUploader(config)
Creates an Uploader instance.
import { createUploader } from 'aliyun-vod-upload-sdk';
const uploader = createUploader(config);UploaderConfig
Parameter | Type | Required | Default | Description |
|
| Provide either this or | — | The credential retrieval callback. For more information, see Credential callback getAuth. |
|
| Provide either this or | — | The STS temporary credential callback (browser direct upload mode). For more information, see getSTS direct upload mode. |
|
|
| — | The VOD service region (for example, |
|
| No |
| The automatic retry policy for failed OSS part uploads. |
|
| No | localStorage | The resumable upload configuration. |
|
| No |
| The number of concurrent OSS parts. |
|
| No |
| The OSS part size in bytes. |
|
| No |
| The network request timeout in milliseconds. This applies to both OSS uploads and VOD OpenAPI calls in STS mode. |
|
| No | — | A custom OSS domain name. |
|
| No |
| When enabled, each part computes and carries |
|
| No |
| The minimum interval, in milliseconds, between two upload credential refreshes. This takes effect only for video uploads (refreshed through |
RetryPolicy
Field | Type | Default | Description |
|
|
| The maximum number of retries |
uploader.upload(file, options?)
Uploads a single file. Returns an UploadTask, which is both a Promise<UploadResult> and carries an .abort() method.
const task = uploader.upload(file, options);UploadOptions
Parameter | Type | Description |
|
| The media asset metadata (title, category, tags, and so on). When |
|
| The standard web cancellation signal. |
|
| The progress callback. |
|
| Overrides the global partSize. |
|
| Overrides the global parallel. |
VodVideoMeta (video metadata)
Field | Type | Description |
|
| The video title. |
|
| The video description. |
|
| The category ID. |
|
| Tags (comma-separated). |
|
| The transcoding template group ID. |
|
| The storage address. |
|
| The thumbnail URL. |
|
| The workflow ID. |
|
| The application ID. |
|
| User-defined data. |
|
| When you upload a |
|
| STS mode only: the transcoding mode (VOD |
VodImageMeta (image metadata)
Field | Type | Description |
|
| The image title |
|
| The image description |
|
| The image type |
|
| The image file extension |
|
| Tags |
|
| The category ID |
|
| The storage address |
VodAttachedMediaMeta (auxiliary media asset metadata)
Field | Type | Description |
|
| Required. |
|
| The file extension. When it is omitted, STS mode derives it from the file name. If neither is available, the parameter is not sent. |
|
| The title (optional for auxiliary media assets; the SDK does not derive it). |
|
| When you upload a |
|
| The description. |
|
| Tags (comma-separated). |
|
| The category ID, comma-separated with a maximum of 5 values (this differs from the video |
|
| The storage address. |
|
| The application ID. |
|
| User-defined data. |
UploadResult (upload result)
Field | Type | Description |
|
| The video ID (returned for video uploads). |
|
| The image ID (returned for image uploads). |
|
| The unified media asset ID across all three pipelines: video = |
|
| OSS ETag. |
|
| The OSS request ID. |
|
| The upload duration in milliseconds. |
|
| The unique upload task ID (useful for after-sales troubleshooting). |
UploadTask
upload() returns an object that is both a Promise<UploadResult> and an object with an .abort() method.
type UploadTask = Promise<UploadResult> & {
abort(): void;
};After chaining, the .abort() method is lost. task.then(fn) returns a plain Promise. To keep cancellation available after chaining, use options.signal.
uploader.dispose()
Releases resources: it cancels all in-progress uploads and purges the internal state.
uploader.dispose();After this call, the uploader instance can no longer be used. Always call this method when a React or Vue component unmounts, to avoid memory leaks.
Credential callback getAuth
type GetAuth = (ctx: AuthContext) => Promise<AuthResult>;AuthContext
Depending on the upload scenario, the SDK passes a different ctx:
ctx.kind | Trigger scenario | Additional ctx fields |
| The first video upload |
|
| A credential refresh during a resumable upload |
|
| An image upload |
|
| An auxiliary media asset (watermark / subtitle / material) |
|
AuthResult
The raw OpenAPI JSON returned by your backend. The SDK decodes it internally:
Field | Type | Required | Description |
|
| Yes | The Base64-encoded STS credential. |
|
| Yes | The Base64-encoded OSS upload URL. |
|
| Required for create-video | The video ID. |
|
| Required for create-image | The image ID. |
|
| Required for create-attached-media | The auxiliary media asset ID. |
|
| No | The image URL (passed through). |
getAuth minimal implementation:
// A single backend route. Note that ctx.file is a File / Blob and JSON.stringify turns it into {},
// so extract the file information that the backend needs (such as fileName) separately
createUploader({
getAuth: ({ file, ...rest }) => fetch('/api/vod/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...rest, fileName: file.name, fileSize: file.size }),
}).then(r => r.json()),
});Automatic fallback when refresh-video fails: when the resumable-upload credential refresh fails, the SDK automatically falls back to create-video and re-uploads. This is completely transparent to the caller.
getSTS direct upload mode
getAuth mode requires your server to call VOD OpenAPI to obtain UploadAuth/UploadAddress. If your server provides only STS temporary credentials, you can use the getSTS mode: the SDK uses the credential to sign VOD OpenAPI calls in the browser, obtains the upload credential, and then uploads the file.
type GetSTS = () => Promise<STSCredential>;
interface STSCredential {
accessKeyId: string;
accessKeySecret: string;
securityToken: string;
}createUploader({
region: 'cn-shanghai', // getSTS mode: required; determines the vod.<region>.aliyuncs.com endpoint
getSTS: async () => {
const { AccessKeyId, AccessKeySecret, SecurityToken } = await fetch('/api/sts').then(r => r.json());
return { accessKeyId: AccessKeyId, accessKeySecret: AccessKeySecret, securityToken: SecurityToken };
},
});Key points:
Must run on HTTPS or localhost: the V3 signature in STS mode relies on the Web Crypto API
crypto.subtleand is unavailable on plain HTTP pages. ThegetAuthmode is not subject to this restriction.Mutually exclusive with
getAuth: you can pass only one of the two.Takes no arguments and carries no
expiration: the SDK does not proactively check whether the STS credential has expired. When VOD returnsInvalidSecurityToken.Expired, the SDK automatically callsgetSTS()once more and retries once.No caching and no concurrent-request deduplication: multiple concurrent
upload()calls each invokegetSTS(). Implement caching yourself if you need it.Title/FileNameare derived by the SDK from the file:FileName=file.name(Blobuploads usemeta.fileName),Title=meta.title ?? FileName; derived values are truncated to 128 characters, whereas an explicitly providedmeta.titleis not truncated.FileSizeis filled in by the SDK: everyCreateUploadVideocall unconditionally includesFileSize=file.size(in v1 you had to pass it yourself inuserData; if you omitted it, VOD had no file size).When a VOD call fails, the error code is
UPLOAD.VOD.CREATE_FAILED/UPLOAD.VOD.REFRESH_FAILED. Thesuggestionfield contains a VOD troubleshooting link. The original VODMessagenever reachesUploadError(it may contain plaintext credentials); it is reported to event tracking only after being redacted.Timeout and retry reuse the
timeout/retry.countsettings. Neither 4xx nor 5xx is retried (the only exception is the expiration code mentioned above).
Error handling
UploadError structure
All upload errors are UploadError instances (they inherit from Error):
import { UploadError } from 'aliyun-vod-upload-sdk';
class UploadError extends Error {
readonly code: string; // Structured error code, such as 'UPLOAD.OSS.ACCESS_DENIED'
readonly message: string; // Error description
readonly suggestion: string; // Fix suggestion (in Chinese)
readonly cause?: unknown; // The underlying original error
readonly uploadTaskId?: string; // Upload task ID (useful for after-sales troubleshooting)
}A user-initiated cancellation is not an UploadError; it is a standard DOMException (name === 'AbortError').
Error codes
Error code format: UPLOAD.{level}.{type}
Error code | Meaning | Suggested fix |
|
| Check whether the getAuth callback correctly returns JSON that contains UploadAuth and UploadAddress. Make sure that the backend service is available and that the response format is correct. |
|
| In STS mode, the getSTS callback failed to obtain temporary credentials. Check whether your getSTS implementation can call your STS service successfully (network connectivity, authentication, and CORS configuration), and whether the returned accessKeyId, accessKeySecret, and securityToken are complete. |
| In STS mode, the | In STS mode, the SDK failed to call the VOD API to create an upload credential. Check whether the region passed to createUploader matches the region of your account, whether the temporary credentials returned by getSTS have VOD permissions (CreateUploadVideo, CreateUploadImage, and CreateUploadAttachedMedia), and whether the media asset parameters in meta are valid. |
| In STS mode, the | In STS mode, the SDK failed to call the VOD API to renew an upload credential. Check whether the temporary credentials returned by getSTS are valid and have the RefreshUploadVideo permission, and whether the media asset for videoId still exists. |
| Invalid configuration: (1) | The configuration is invalid. Make sure that you pass only one of getAuth and getSTS to createUploader. In STS mode (when you pass getSTS), you must provide a non-empty region that matches the region of your account (for example, cn-shanghai). When you upload an auxiliary media asset, meta.businessType must be a non-empty string (such as watermark, subtitle, or material). |
| OSS permission error (403) | OSS access was denied. Check whether the upload credential (STS Token) is valid and has not expired, and whether the RAM policy grants OSS write permissions. |
| The bucket does not exist | The OSS bucket does not exist. Check whether the bucket name in the upload URL is correct, and confirm that the bucket has been created in the corresponding region. |
| The multipart upload session has expired | The multipart upload session has expired (it may have been longer than 24 hours). The SDK automatically re-uploads, so no manual action is required. |
| Unknown OSS error | An unknown error occurred during the OSS upload. Check the browser console for the detailed error message. |
| The request timed out | The network request timed out. Open the Network panel in your browser developer tools to inspect the failed request, check that the network connection is stable, or try increasing the timeout value. |
| Network connection error | A network connection error occurred. Open the Network panel in your browser developer tools to check the status code and response of the failed request, confirm that the browser can reach the OSS service address, and check whether a proxy or firewall is blocking the request. |
| The browser is offline | The browser detected that it is currently offline. Open the Network panel in your browser developer tools to confirm the network status, then reconnect to the network and retry the upload. |
| The file size is 0 | The file size is 0, so an empty file cannot be uploaded. Check that the file was selected correctly. |
| The Uploader instance has been destroyed | The Uploader instance has been destroyed and can no longer be used. Call createUploader again to create a new instance. |
Use error code constants
Use the ErrorCode constants instead of string literals:
import { ErrorCode, UploadError } from 'aliyun-vod-upload-sdk';
try {
await uploader.upload(file);
} catch (e) {
if (e instanceof UploadError) {
switch (e.code) {
case ErrorCode.AUTH_GET_AUTH_FAILED:
showToast('Failed to obtain the credential. Refresh the page and try again');
break;
case ErrorCode.NETWORK_TIMEOUT:
case ErrorCode.NETWORK_ERROR:
showToast('Network error. Check your connection and try again');
break;
case ErrorCode.OSS_ACCESS_DENIED:
showToast('Insufficient upload permissions. Contact your administrator');
break;
default:
showToast(`Upload failed: ${e.suggestion || e.message}`);
}
}
}Troubleshooting
Every UploadError carries an uploadTaskId, which is the global correlation ID of the entire upload. Provide it to Alibaba Cloud after-sales support to locate the issue quickly:
catch (e) {
if (e instanceof UploadError) {
// Send this to your technical support team
const diagnostic = {
code: e.code,
message: e.message,
uploadTaskId: e.uploadTaskId,
suggestion: e.suggestion,
};
reportToSupport(diagnostic);
}
}UploadResult.uploadTaskId can also be used to correlate logs after a successful upload:
const result = await uploader.upload(file);
myLogger.info('Upload succeeded', { videoId: result.videoId, uploadTaskId: result.uploadTaskId });