Upload files using the JavaScript SDK

Updated at:

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

Quick integration

Installation

npm install aliyun-vod-upload-sdk

The 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

{ UploadAuth, UploadAddress, VideoId }

Refresh a video upload credential

RefreshUploadVideo

{ UploadAuth, UploadAddress, VideoId }

Create an image upload credential

CreateUploadImage

{ UploadAuth, UploadAddress, ImageId }

Create an auxiliary media asset upload credential

CreateUploadAttachedMedia

{ UploadAuth, UploadAddress, MediaId }

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 = MediaId

businessType / mediaExt and related fields are described below:

Field

Description

businessType

Required. The value is passed through to VOD as is (documented values: watermark / subtitle / material). The SDK does not validate the enumeration, so you do not need to upgrade the SDK when VOD adds a business type

mediaExt

Optional. When it is omitted, STS mode derives it from the file name extension (sub.srt → srt). You need to pass it explicitly only when the file name has no extension, or when you upload a Blob.

title / fileName / description / tags / cateIds / storageLocation / appId / userData

Optional. These fields are equivalent to the video meta fields. Note that cateIds is a comma-separated string (up to 5 values), which differs from the video cateId: number.

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 pass businessType does 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:

  1. Stores the progress of completed parts in localStorage.

  2. After the page refreshes, call upload(file) again, and the upload automatically continues from where it stopped.

  3. 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),
  ]),
});
Note

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

getAuth

GetAuth

Provide either this or getSTS.

—

The credential retrieval callback. For more information, see Credential callback getAuth.

getSTS

GetSTS

Provide either this or getAuth.

—

The STS temporary credential callback (browser direct upload mode). For more information, see getSTS direct upload mode.

region

string

getSTS mode: required

—

The VOD service region (for example, cn-shanghai), which determines the vod.<region>.aliyuncs.com endpoint.

retry

RetryPolicy

No

{count: 3}

The automatic retry policy for failed OSS part uploads.

checkpoint

false | { store?: CheckpointStore }

No

localStorage

The resumable upload configuration. false disables it; { store } injects a custom store.

parallel

number

No

4

The number of concurrent OSS parts.

partSize

number

No

1048576 (1MB)

The OSS part size in bytes.

timeout

number

No

60000

The network request timeout in milliseconds. This applies to both OSS uploads and VOD OpenAPI calls in STS mode.

cname

string

No

—

A custom OSS domain name.

enableMD5

boolean

No

false

When enabled, each part computes and carries Content-MD5, and OSS verifies data integrity (equivalent to ali-oss multipartUpload with disabledMD5: false). This adds CPU overhead.

refreshSTSTokenInterval

number

No

300000 (5min)

The minimum interval, in milliseconds, between two upload credential refreshes. This takes effect only for video uploads (refreshed through refresh-video) and is passed through to ali-oss refreshSTSTokenInterval. Refreshes are request-driven: the SDK checks only before it issues an OSS request, so no request means no refresh, and a slow upload request lengthens the actual refresh interval. Note that this governs the OSS upload credential, not the STS credential of the user. 0, a negative number, or NaN is normalized back to the default value.

RetryPolicy

Field

Type

Default

Description

count

number

3

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

meta

VodVideoMeta | VodImageMeta | VodAttachedMediaMeta

The media asset metadata (title, category, tags, and so on). When businessType is present, the upload goes through the auxiliary media asset pipeline.

signal

AbortSignal

The standard web cancellation signal.

onProgress

(percent, loaded, total) => void

The progress callback. percent ranges from 0 to 1.

partSize

number

Overrides the global partSize.

parallel

number

Overrides the global parallel.

VodVideoMeta (video metadata)

Field

Type

Description

title

string

The video title.

description

string

The video description.

cateId

number

The category ID.

tags

string

Tags (comma-separated).

templateGroupId

string

The transcoding template group ID.

storageLocation

string

The storage address.

coverUrl

string

The thumbnail URL.

workflowId

string

The workflow ID.

appId

string

The application ID.

userData

Record<string, unknown>

User-defined data.

fileName

string

When you upload a Blob (which has no name) in STS mode, this provides the FileName value.

transCodeMode

string

STS mode only: the transcoding mode (VOD TransCodeMode). If it is omitted, the parameter is not sent.

VodImageMeta (image metadata)

Field

Type

Description

title

string

The image title

description

string

The image description

imageType

'default' | 'cover' | 'watermark'

The image type

imageExt

string

The image file extension

tags

string

Tags

cateId

number

The category ID

storageLocation

string

The storage address

VodAttachedMediaMeta (auxiliary media asset metadata)

Field

Type

Description

businessType

string

Required. watermark/subtitle/material, and so on. The value is passed through without validation. The presence of this field routes the upload to the auxiliary media asset pipeline.

mediaExt

string

The file extension. When it is omitted, STS mode derives it from the file name. If neither is available, the parameter is not sent.

title

string

The title (optional for auxiliary media assets; the SDK does not derive it).

fileName

string

When you upload a Blob (which has no name) in STS mode, this provides the FileName value.

description

string

The description.

tags

string

Tags (comma-separated).

cateIds

string

The category ID, comma-separated with a maximum of 5 values (this differs from the video cateId: number).

storageLocation

string

The storage address.

appId

string

The application ID.

userData

Record<string, unknown>

User-defined data.

UploadResult (upload result)

Field

Type

Description

videoId

string?

The video ID (returned for video uploads).

imageId

string?

The image ID (returned for image uploads).

mediaId

string?

The unified media asset ID across all three pipelines: video = VideoId, image = ImageId, auxiliary media asset = MediaId.

etag

string

OSS ETag.

requestId

string

The OSS request ID.

durationMs

number

The upload duration in milliseconds.

uploadTaskId

string

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;
};
Important

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

'create-video'

The first video upload

file, meta?.

'refresh-video'

A credential refresh during a resumable upload

file, videoId.

'create-image'

An image upload

file, meta?.

'create-attached-media'

An auxiliary media asset (watermark / subtitle / material)

file, meta? (includes businessType).

AuthResult

The raw OpenAPI JSON returned by your backend. The SDK decodes it internally:

Field

Type

Required

Description

UploadAuth

string

Yes

The Base64-encoded STS credential.

UploadAddress

string

Yes

The Base64-encoded OSS upload URL.

VideoId

string

Required for create-video

The video ID.

ImageId

string

Required for create-image

The image ID.

MediaId

string

Required for create-attached-media

The auxiliary media asset ID.

ImageURL

string

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.subtle and is unavailable on plain HTTP pages. The getAuth mode 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 returns InvalidSecurityToken.Expired, the SDK automatically calls getSTS() once more and retries once.

  • No caching and no concurrent-request deduplication: multiple concurrent upload() calls each invoke getSTS(). Implement caching yourself if you need it.

  • Title / FileName are derived by the SDK from the file: FileName=file.name (Blob uploads use meta.fileName), Title=meta.title ?? FileName; derived values are truncated to 128 characters, whereas an explicitly provided meta.title is not truncated.

  • FileSize is filled in by the SDK: every CreateUploadVideo call unconditionally includes FileSize=file.size (in v1 you had to pass it yourself in userData; 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. The suggestion field contains a VOD troubleshooting link. The original VOD Message never reaches UploadError (it may contain plaintext credentials); it is reported to event tracking only after being redacted.

  • Timeout and retry reuse the timeout/retry.count settings. 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

UPLOAD.AUTH.GET_AUTH_FAILED

getAuth callback throws an error or returns a malformed structure

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.

UPLOAD.AUTH.GET_STS_FAILED

getSTS callback throws an error (STS mode)

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.

UPLOAD.VOD.CREATE_FAILED

In STS mode, the CreateUploadVideo/CreateUploadImage/CreateUploadAttachedMedia call fails

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.

UPLOAD.VOD.REFRESH_FAILED

In STS mode, the RefreshUploadVideo call fails

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.

UPLOAD.CONFIG.INVALID

Invalid configuration: (1) createUploader does not provide exactly one of getAuth/getSTS, or STS mode is missing region (thrown synchronously at build time); (2) the meta.businessType key exists but its value is not a non-empty string (at upload time this returns a rejected UploadTask)

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).

UPLOAD.OSS.ACCESS_DENIED

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.

UPLOAD.OSS.NO_SUCH_BUCKET

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.

UPLOAD.OSS.NO_SUCH_UPLOAD

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.

UPLOAD.OSS.UNKNOWN

Unknown OSS error

An unknown error occurred during the OSS upload. Check the browser console for the detailed error message.

UPLOAD.NETWORK.TIMEOUT

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.

UPLOAD.NETWORK.ERROR

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.

UPLOAD.NETWORK.OFFLINE

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.

UPLOAD.FILE.EMPTY

The file size is 0

The file size is 0, so an empty file cannot be uploaded. Check that the file was selected correctly.

UPLOAD.INTERNAL.DISPOSED

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 });