@capgo/capacitor-uploader

中文文档
8.3.27发布于 2026/11/09MPL-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 9.2万

Upload file natively

原始使用文档
文档目录22 节
  1. ➡️ Get started for free
  2. Key features
  3. Uploader Plugin
  4. Documentation
  5. Compatibility
  6. Install
  7. Android
  8. iOS
  9. Example S3 upload
  10. Example upload to a custom server
  11. Example multi-file multipart upload
  12. Example with Capacitor Camera preview
  13. API
  14. iOS setup
  15. startUpload(...)
  16. uploadMultipart(...)
  17. removeUpload(...)
  18. addListener('events', ...)
  19. acknowledgeEvent(...)
  20. getPluginVersion()
  21. Interfaces
  22. Credits:

@capgo/capacitor-uploader

Upload files from your Capacitor app with native background uploads that keep going when the app is closed, with progress events and retries.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-uploader in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-uploader to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-uploader for Capacitor apps

Key features

  • Uploads: startUpload() sends a file with PUT or POST, custom headers and parameters.
  • Multipart: uploadMultipart() sends a file as multipart/form-data.
  • Progress events: the events listener reports progress, completion and errors.
  • Control: removeUpload() cancels an upload, maxRetries retries failures.
  • Background: a background URLSession on iOS and an upload service with a notification on Android.
  • Platforms: iOS, Android and Web. Web uploads with fetch() while the page is open, without native background uploads.

Uploader Plugin

This plugin provides a flexible way to upload natively files to various servers, including S3 with presigned URLs.

Can be used in combination with the Capacitor Camera preview To upload file in reliable manner instead of reading them in buffer of webview and then upload in JS.

On the web, file paths support IndexedDB (IDB) semantic paths using the following format:
idb://[database-name]/[collection-name]/[key]
This allows seamless integration with IndexedDB for storing and retrieving files.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/uploader/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-uploader` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capgo/capacitor-uploader
npx cap sync

Android

Add the following to your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

iOS

On iOS the plugin uploads through a background URLSession using the identifier CapacitorUploaderBackgroundSession.

Uploads often work without extra Info.plist keys. To allow the system to wake your app when background transfers finish, add the fetch background mode:

<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
</array>

Do not add the processing background mode for this plugin alone. App Store Connect requires BGTaskSchedulerPermittedIdentifiers whenever processing is declared, and this plugin does not register BGTaskScheduler tasks. If your app already includes processing (for example from older documentation) and validation fails, add:

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>CapacitorUploaderBackgroundSession</string>
</array>

See issue #115 for context.

Example S3 upload

import { Uploader } from '@capgo/capacitor-uploader';

async function uploadToS3(filePath: string, presignedUrl: string, fields: Record<string, string>) {
  try {
    const { id } = await Uploader.startUpload({
      filePath: filePath,
      serverUrl: presignedUrl,
      method: 'PUT',
      parameters: fields,
      notificationTitle: 'Uploading to S3'
    });

    console.log('Upload started with ID:', id);

    // Listen for upload events
    Uploader.addListener('events', (event: UploadEvent) => {
      if (event.name === 'uploading') {
        console.log(`Upload progress: ${event.payload.percent}%`);
      } else if (event.name === 'completed') {
        console.log('Upload completed successfully');
      } else if (event.name === 'failed') {
        console.error('Upload failed:', event.payload.error);
      }
    });

  } catch (error) {
    console.error('Failed to start upload:', error);
  }
}

Example upload to a custom server

import { Uploader } from '@capgo/capacitor-uploader';

async function uploadToCustomServer(filePath: string, serverUrl: string) {
  try {
    // Start the upload
    const { id } = await Uploader.startUpload({
      filePath: filePath,
      serverUrl: serverUrl,
      method: 'POST',
      headers: {
        'Authorization': 'Bearer your-auth-token-here'
      },
      parameters: {
        'user_id': '12345',
        'file_type': 'image'
      },
      notificationTitle: 'Uploading to Custom Server',
      maxRetries: 3
    });

    console.log('Upload started with ID:', id);

    // Listen for upload events
    Uploader.addListener('events', (event) => {
      switch (event.name) {
        case 'uploading':
          console.log(`Upload progress: ${event.payload.percent}%`);
          break;
        case 'completed':
          console.log('Upload completed successfully');
          console.log('Server response status code:', event.payload.statusCode);
          break;
        case 'failed':
          console.error('Upload failed:', event.payload.error);
          break;
      }
    });

    // Optional: Remove the upload if needed
    // await Uploader.removeUpload({ id: id });

  } catch (error) {
    console.error('Failed to start upload:', error);
  }
}

// Usage
const filePath = 'file:///path/to/your/file.jpg';
const serverUrl = 'https://your-custom-server.com/upload';
uploadToCustomServer(filePath, serverUrl);

Example multi-file multipart upload

import { Uploader } from '@capgo/capacitor-uploader';

const { id } = await Uploader.startUpload({
  serverUrl: 'https://api.example.com/upload',
  method: 'POST',
  uploadType: 'multipart',
  files: [
    { filePath: 'file:///...photo1.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' },
    { filePath: 'file:///...photo2.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' },
  ],
  parameters: { albumId: '7' },
  headers: { Authorization: 'Bearer token' },
});
console.log('Upload started with ID:', id);

Example with Capacitor Camera preview

Documentation for the Capacitor Camera preview

  import { CameraPreview } from '@capgo/camera-preview'
  import { Uploader } from '@capgo/capacitor-uploader';


  async function record() {
    await CameraPreview.startRecordVideo({ storeToFile: true })
    await new Promise(resolve => setTimeout(resolve, 5000))
    const fileUrl = await CameraPreview.stopRecordVideo()
    console.log(fileUrl.videoFilePath)
    await uploadVideo(fileUrl.videoFilePath)
  }

  async function uploadVideo(filePath: string) {
    Uploader.addListener('events', (event) => {
      switch (event.name) {
        case 'uploading':
          console.log(`Upload progress: ${event.payload.percent}%`);
          break;
        case 'completed':
          console.log('Upload completed successfully');
          console.log('Server response status code:', event.payload.statusCode);
          break;
        case 'failed':
          console.error('Upload failed:', event.payload.error);
          break;
      }
    });
    try {
      const result = await Uploader.startUpload({
        filePath,
        serverUrl: 'S#_PRESIGNED_URL',
        method: 'PUT',
        headers: {
          'Content-Type': 'video/mp4',
        },
        mimeType: 'video/mp4',
      });
      console.log('Video uploaded successfully:', result.id);
    } catch (error) {
      console.error('Error uploading video:', error);
      throw error;
    }
  }

API

Capacitor Uploader Plugin for uploading files with background support and progress tracking.

iOS setup

On iOS the native layer uses a background URLSession with the identifier CapacitorUploaderBackgroundSession. Many apps can upload without adding UIBackgroundModes; add fetch when you need uploads to continue after the app is suspended.

App Store Connect rejects builds that declare UIBackgroundModes → processing without BGTaskSchedulerPermittedIdentifiers. This plugin does not schedule BGTaskScheduler work, so avoid processing unless another feature needs it. If processing is present (for example from older setup guides), include CapacitorUploaderBackgroundSession in BGTaskSchedulerPermittedIdentifiers in your app's Info.plist.

startUpload(...)

startUpload(options: uploadOption) => Promise<{ id: string; }>

Start uploading a file to a server.

The upload will continue in the background even if the app is closed or backgrounded. Listen to upload events to track progress, completion, or failure.

ParamTypeDescription
optionsuploadOption- Configuration for the upload

Returns: Promise<{ id: string; }>

Since: 0.0.1


uploadMultipart(...)

uploadMultipart(options: UploadMultipartOptions) => Promise<{ id: string; }>

Start uploading a single file as multipart/form-data.

This is a convenience API for backends that expect a named file field and additional form fields. Existing startUpload binary uploads are unchanged.

ParamTypeDescription
optionsUploadMultipartOptions- Configuration for the multipart upload

Returns: Promise<{ id: string; }>

Since: 8.3.2


removeUpload(...)

removeUpload(options: { id: string; }) => Promise<void>

Cancel and remove an ongoing upload.

This will stop the upload if it's in progress and clean up resources.

ParamTypeDescription
options{ id: string; }- Object containing the upload ID to remove

Since: 0.0.1


addListener('events', ...)

addListener(eventName: 'events', listenerFunc: (state: UploadEvent) => void) => Promise<PluginListenerHandle>

Listen for upload progress and status events.

Events are fired for:

  • Upload progress updates (with percent)
  • Upload completion (with statusCode)
  • Upload failure (with error and statusCode)
ParamTypeDescription
eventName'events'- Must be 'events'
listenerFunc(state: UploadEvent) => void- Callback function to handle upload events

Returns: Promise<PluginListenerHandle>

Since: 0.0.1


acknowledgeEvent(...)

acknowledgeEvent(options: { eventId: string; }) => Promise<void>

Acknowledge receipt of an upload event and remove it from the plugin cache.

Completed and failed events are stored in the plugin's persistent cache so they can be re-delivered if the app is closed or backgrounded before the event is processed. Call this method after successfully handling a 'completed' or 'failed' event to prevent it from being re-broadcast the next time the plugin initialises.

Progress ('uploading') events do not have an eventId and do not need to be acknowledged.

ParamTypeDescription
options{ eventId: string; }- Object containing the eventId to acknowledge

Since: 0.0.2


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns: Promise<{ version: string; }>

Since: 0.0.1


Interfaces

uploadOption

PropTypeDescriptionDefaultSince
filePathstringThe local file path of the file to upload. Can be a file:// URL or an absolute path. If you need to upload multiple files in a single multipart request, use files.0.0.1
filesUploadFileOption[]Multiple files to upload in a single request. When provided, uploads are sent as multipart/form-data with one part per file. Use fieldName to control each part name (e.g. images[]). Note: PUT uploads (e.g. presigned S3 URLs) only support a single file.0.0.3
serverUrlstringThe server URL endpoint where the file should be uploaded.0.0.1
notificationTitlestringThe title of the upload notification shown to the user. Android only.'Uploading'0.0.1
headers{ [key: string]: string; }HTTP headers to send with the upload request. Useful for authentication tokens, content types, etc.0.0.1
method'PUT' | 'POST'The HTTP method to use for the upload request.'POST'0.0.1
mimeTypestringThe MIME type of the file being uploaded. If not specified, the plugin will attempt to determine it automatically.0.0.1
parameters{ [key: string]: string; }Additional form parameters to send with the upload request. These will be included as form data in multipart uploads.0.0.1
maxRetriesnumberThe maximum number of times to retry the upload if it fails.00.0.1
uploadType'binary' | 'multipart'The type of upload to perform. - 'binary': Uploads the file as raw binary data in the request body - 'multipart': Uploads the file as multipart/form-data'binary' when method is 'PUT', otherwise 'multipart'0.0.2
fileFieldstringThe form field name for the file when using multipart upload type. Only used when uploadType is 'multipart'. For multi-file uploads via files, this is used as the default field name when a file entry does not specify fieldName.'file'0.0.2

UploadFileOption

Configuration options for uploading a file.

PropTypeDescriptionSince
filePathstringThe local file path of the file to upload. Can be a file:// URL or an absolute path.0.0.3
fieldNamestringThe form field name for the file part when using multipart upload. If omitted, uploadOption.fileField is used (defaults to 'file').0.0.3
mimeTypestringThe MIME type of this file. If not specified, the plugin will attempt to determine it automatically.0.0.3

UploadMultipartOptions

Options for starting a single-file multipart upload.

PropTypeDescriptionSince
urlstringThe server URL endpoint where the multipart request should be sent.8.3.2
filePathstringThe local file path of the file to upload. Can be a file:// URL or an absolute path.8.3.2
fieldNamestringThe form field name for the uploaded file part.8.3.2
fields{ [key: string]: string; }Additional form fields to include in the multipart request.8.3.2
headers{ [key: string]: string; }HTTP headers to send with the upload request.8.3.2

PluginListenerHandle

PropType
remove() => Promise<void>

UploadEvent

Event emitted during the upload lifecycle.

PropTypeDescriptionSince
name'uploading' | 'completed' | 'failed'The current status of the upload. - 'uploading': Upload is in progress - 'completed': Upload finished successfully - 'failed': Upload encountered an error0.0.1
payload{ percent?: number; error?: string; statusCode?: number; }Additional data about the upload event.0.0.1
idstringUnique identifier for this upload task.0.0.1
eventIdstringUnique identifier for this specific event instance. Only present on 'completed' and 'failed' events. Used with acknowledgeEvent() to confirm receipt and remove the event from the plugin cache. Progress ('uploading') events do not have an eventId and are not persisted.0.0.2

Credits:

For the inspiration and the code on ios: https://github.com/Vydia/react-native-background-upload/tree/master For the API definition: https://www.npmjs.com/package/cordova-plugin-background-upload-put-s3

版本与发布记录

@capgo/capacitor-uploader 共发布 129 个版本,首次发布于 2024/09/04;过去 12 个月发布了 79 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.3.27latest2026/11/09今天
8.3.262026/10/1525 天前
8.3.252026/10/1327 天前
8.3.242026/10/1228 天前
8.3.232026/10/091 个月前
8.3.222026/10/091 个月前

关于 @capgo/capacitor-uploader 的常见问题

@capgo/capacitor-uploader 是什么?

Upload file natively

如何安装 @capgo/capacitor-uploader?

在项目目录运行 npm install @capgo/capacitor-uploader,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-uploader 支持 TypeScript 吗?

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

@capgo/capacitor-uploader 支持 ESM 还是 CommonJS?

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

@capgo/capacitor-uploader 可以商用吗?

@capgo/capacitor-uploader 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-uploader 的下载量有多少?

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

@capgo/capacitor-uploader 还在维护吗?

最新版本 8.3.27 发布于 2026/11/09(今天);至今共发布 129 个版本,其中过去 12 个月发布了 79 个;首次发布于 2024/09/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。