@api.video/video-uploader

中文文档
1.1.6发布于 2023/10/31MITTypeScriptESM + CJS近 30 天下载 6752

api.video video uploader

原始使用文档
文档目录21 节
  1. Installation
  2. Installation method #1: requirejs
  3. Installation method #2: typescript
  4. Simple include in a javascript project
  5. Instanciation
  6. Options
  7. Example
  8. Methods
  9. upload()
  10. onProgress()
  11. cancel()
  12. onPlayable()
  13. Instanciation
  14. Options
  15. Example
  16. Methods
  17. uploadPart(file: Blob)
  18. uploadLastPart(file: Blob)
  19. onProgress()
  20. cancel()
  21. onPlayable()

badge   badge   badge

api.video typescript video uploader

npm ts

api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in your app.

Table of contents

Project description

Typescript library to upload videos to api.video using delegated upload token (or usual access token) from the front-end.

It allows you to upload videos in two ways:

  • standard upload: to send a whole video file in one go
  • progressive upload: to send a video file by chunks, without needing to know the final size of the video file

Getting started

Installation

Installation method #1: requirejs

If you use requirejs you can add the library as a dependency to your project with

$ npm install --save @api.video/video-uploader

You can then use the library in your script:

// standard upload:
var { VideoUploader } = require('@api.video/video-uploader');

var uploader = new VideoUploader({
    // ... (see bellow)
}); 

// progressive upload:
var { ProgressiveUploader } = require('@api.video/video-uploader');

var uploader = new ProgressiveUploader({
    // ... (see bellow)
}); 

Installation method #2: typescript

If you use Typescript you can add the library as a dependency to your project with

$ npm install --save @api.video/video-uploader

You can then use the library in your script:

// standard upload:
import { VideoUploader } from '@api.video/video-uploader'

const uploader = new VideoUploader({
    // ... (see bellow)
});

// progressive upload:
import { ProgressiveUploader } from '@api.video/video-uploader'

const uploader = new ProgressiveUploader({
    // ... (see bellow)
});

Simple include in a javascript project

Include the library in your HTML file like so:

<head>
    ...
    <script src="https://unpkg.com/@api.video/video-uploader" defer></script>
</head>

Then, once the window.onload event has been trigered, create your player using new VideoUploader():

...
<form>
    <input type="file" id="input" onchange="uploadFile(this.files)">
</form>
<script type="text/javascript">
    function uploadFile(files) {
        new VideoUploader({
            file: files[0],
            uploadToken: "YOUR_DELEGATED_TOKEN"
        }).upload();
    }
</script>

Documentation - Standard upload

Instanciation

Options

The upload library is instanciated using an options object. Options to provide depend on the way you want to authenticate to the API: either using a delegated upload token (recommanded), or using a usual access token.

Using delegated upload tokens for authentication is best options when uploading from the client side. To know more about delegated upload token, read the dedicated article on api.video's blog: Delegated Uploads.

Option nameMandatoryTypeDescription
uploadTokenyesstringyour upload token
videoIdnostringid of an existing video
common options (see bellow)

Using an access token (discouraged):

Warning: be aware that exposing your access token client-side can lead to huge security issues. Use this method only if you know what you're doing :).

Option nameMandatoryTypeDescription
accessTokenyesstringyour access token
refreshTokennostringyour refresh token (please not that if you don't provide a refresh token, your upload may fails due to the access token lifetime of 60 minutes)
videoIdyesstringid of an existing video
common options (see bellow)

Using an API key (strongly discouraged):

Warning: be aware that exposing your API key client-side can lead to huge security issues. Use this method only if you know what you're doing :).

Option nameMandatoryTypeDescription
API Keyyesstringyour api.video API key
videoIdyesstringid of an existing video
common options (see bellow)

Common options

Option nameMandatoryTypeDescription
fileyesFilethe file you want to upload
videoNamenostringthe name of your video (overrides the original file name for regular uploads, overrides the default "file" name for progressive uploads)
chunkSizenonumbernumber of bytes of each upload chunk (default: 50MB, min: 5MB, max: 128MB)
apiHostnostringapi.video host (default: ws.api.video)
retriesnonumbernumber of retries when an API call fails (default: 5)
retryStrategyno(retryCount: number, error: VideoUploadError) => number | nullfunction that returns the number of ms to wait before retrying a failed upload. Returns null to stop retrying
maxVideoDurationnonumbermaximum duration allowed for the file (in seconds)

Example

    const uploader = new VideoUploader({
        file: files[0],
        uploadToken: "YOUR_DELEGATED_TOKEN",
        chunkSize: 1024*1024*10, // 10MB
        retries: 10,
    });

Methods

upload()

The upload() method starts the upload. It takes no parameter. It returns a Promise that resolves once the file is uploaded. If an API call fails more than the specified number of retries, then the promise is rejected. On success, the promise embeds the video object returned by the API. On fail, the promise embeds the status code & error message returned by the API.

Example

    // ... uploader instanciation

    uploader.upload()
        .then((video) => console.log(video))
        .catch((error) => console.log(error.status, error.message));

onProgress()

The onProgress() method let you defined an upload progress listener. It takes a callback function with one parameter: the onProgress events. An onProgress event contains the following attributes:

  • uploadedBytes (number): total number of bytes uploaded for this upload
  • totalBytes (number): total size of the file
  • chunksCount (number): number of upload chunks
  • chunksBytes (number): size of a chunk
  • currentChunk (number): index of the chunk being uploaded
  • currentChunkUploadedBytes (number): number of bytes uploaded for the current chunk

cancel()

The cancel() method cancels the upload. It takes no parameter.

Example

    // ... uploader instanciation
    
    uploader.onProgress((event) => {
        console.log(`total number of bytes uploaded for this upload: ${event.uploadedBytes}.`);
        console.log(`total size of the file: ${event.totalBytes}.`);
        console.log(`number of upload chunks: ${event.chunksCount} .`);
        console.log(`size of a chunk: ${event.chunksBytes}.`);
        console.log(`index of the chunk being uploaded: ${event.currentChunk}.`);
        console.log(`number of bytes uploaded for the current chunk: ${event.currentChunkUploadedBytes}.`);
    });

onPlayable()

The onPlayable() method let you defined a listener that will be called when the video is playable. It takes a callback function with one parameter: the video object returned by the API.

Example

    <div id="player-container"></div>

    <script>
        // ... uploader instanciation
    
        uploader.onPlayable((video) => {
            // the video is playable, we can display the player
            document.getElementById('player-container').innerHTML = v.assets.iframe;
        });
    </script>

Documentation - Progressive upload

Instanciation

Options

The progressive upload object is instanciated using an options object. Options to provide depend on the way you want to authenticate to the API: either using a delegated upload token (recommanded), or using a usual access token.

Using delegated upload tokens for authentication is best options when uploading from the client side. To know more about delegated upload token, read the dedicated article on api.video's blog: Delegated Uploads.

Option nameMandatoryTypeDescription
uploadTokenyesstringyour upload token
videoIdnostringid of an existing video
common options (see bellow)

Using an access token (discouraged):

Warning: be aware that exposing your access token client-side can lead to huge security issues. Use this method only if you know what you're doing :).

Option nameMandatoryTypeDescription
accessTokenyesstringyour access token
videoIdyesstringid of an existing video
common options (see bellow)

Common options

Option nameMandatoryTypeDescription
apiHostnostringapi.video host (default: ws.api.video)
retriesnonumbernumber of retries when an API call fails (default: 5)
retryStrategyno(retryCount: number, error: VideoUploadError) => number | nullfunction that returns the number of ms to wait before retrying a failed upload. Returns null to stop retrying
preventEmptyPartsnobooleanif true, the upload will succeed even if an empty Blob is passed to uploadLastPart(). This may alter performances a bit in some cases (default: false)
mergeSmallPartsBeforeUploadnobooleanif false, parts smaller than 5MB will not be merged before upload, resulting in an error (default: true)

Example

    const uploader = new ProgressiveUploader({
        uploadToken: "YOUR_DELEGATED_TOKEN",
        retries: 10,
    });

Methods

uploadPart(file: Blob)

The upload() method starts the upload. It takes no parameter. It returns a Promise that resolves once the file is uploaded. If an API call fails more than the specified number of retries, then the promise is rejected. On success, the promise embeds the video object returned by the API. On fail, the promise embeds the status code & error message returned by the API.

Example

    // ... uploader instanciation

    uploader.uploadPart(blob)
        .catch((error) => console.log(error.status, error.message));

uploadLastPart(file: Blob)

The upload() method starts the upload. It takes no parameter. It returns a Promise that resolves once the file is uploaded. If an API call fails more than the specified number of retries, then the promise is rejected. On success, the promise embeds the video object returned by the API. On fail, the promise embeds the status code & error message returned by the API.

Example

    // ... uploader instanciation

    uploader.uploadLastPart(blob)
        .then((video) => console.log(video))
        .catch((error) => console.log(error.status, error.message));

onProgress()

The onProgress() method let you defined an upload progress listener. It takes a callback function with one parameter: the onProgress events. An onProgress event contains the following attributes:

  • uploadedBytes (number): total number of bytes uploaded for this upload
  • totalBytes (number): total size of the file
  • part (number): index of the part being uploaded

Example

    // ... uploader instanciation
    
    uploader.onProgress((event) => {
        console.log(`total number of bytes uploaded for this upload: ${event.uploadedBytes}.`);
        console.log(`total size of the file: ${event.totalBytes}.`);
        console.log(`current part: ${event.part}.`);
    });

cancel()

The cancel() method cancels the upload. It takes no parameter.

onPlayable()

The onPlayable() method let you defined a listener that will be called when the video is playable. It takes a callback function with one parameter: the video object returned by the API.

Example

    <div id="player-container"></div>

    <script>
        // ... uploader instanciation
    
        uploader.onPlayable((video) => {
            // the video is playable, we can display the player
            document.getElementById('player-container').innerHTML = v.assets.iframe;
        });
    </script>

Static wrapper

For situations where managing object instances is impractical, consider using the UploaderStaticWrapper class, which offers static method equivalents for all functionalities.

版本与发布记录

@api.video/video-uploader 共发布 25 个版本,首次发布于 2021/06/30;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.1.6latest2023/10/313 年前
1.1.52023/10/263 年前
1.1.42023/08/213 年前
1.1.32023/01/243 年前
1.1.22023/01/193 年前
1.1.12023/01/183 年前

关于 @api.video/video-uploader 的常见问题

@api.video/video-uploader 是什么?

api.video video uploader

如何安装 @api.video/video-uploader?

在项目目录运行 npm install @api.video/video-uploader,或使用 pnpm add / yarn add / bun add。

@api.video/video-uploader 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@api.video/video-uploader 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@api.video/video-uploader 可以商用吗?

@api.video/video-uploader 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@api.video/video-uploader 的下载量有多少?

根据 npm 官方下载统计,@api.video/video-uploader 在 2026/10/06 – 2026/11/04 这 30 天内被下载 6,752 次,日均约 225 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@api.video/video-uploader 还在维护吗?

最新版本 1.1.6 发布于 2023/10/31(3 年前);至今共发布 25 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/06/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。