Saltar al contenido

Primeros pasos

GitHub

Puedes usar nuestro setup asistido por IA para instalar el plugin. Añade las skills de Capgo a tu herramienta de IA con el siguiente comando:

Ventana de terminal
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Luego usa el siguiente prompt:

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

Si prefieres la configuración manual, instala el plugin ejecutando estos comandos y sigue las instrucciones de cada plataforma:

Ventana de terminal
bun add @capgo/capacitor-uploader
bunx cap sync
import { Uploader } from '@capgo/capacitor-uploader';

Inicia una subida, suscríbete a events, y rastrea la subida recibida id.

import { Uploader } from '@capgo/capacitor-uploader';
let uploadId = '';
const listener = await Uploader.addListener('events', async (event) => {
if (event.id !== uploadId) return;
if (event.name === 'uploading') {
console.log(event.payload.percent);
}
if (event.name === 'completed' || event.name === 'failed') {
if (event.eventId) {
await Uploader.acknowledgeEvent({ eventId: event.eventId });
}
await listener.remove();
}
});
const { id } = await Uploader.startUpload({
filePath: 'file:///data/user/0/.../scan.jpg',
serverUrl: 'https://api.example.com/v1/assets',
method: 'POST',
headers: { Authorization: 'Bearer token' },
maxRetries: 3,
});
uploadId = id;

PUT las subidas admiten un solo archivo. Usa la URL firmada como serverUrl y establece method: 'PUT'.

await Uploader.startUpload({
filePath: capturedUri,
serverUrl: presignedUrl,
method: 'PUT',
headers: { 'Content-Type': 'image/jpeg' },
});
await Uploader.uploadMultipart({
url: 'https://api.example.com/upload',
filePath: localPath,
fieldName: 'file',
fields: { userId: '42', kind: 'receipt' },
headers: { Authorization: 'Bearer token' },
});
  • Varios archivos: usa el files array en startUpload para una solicitud multipart. PUT no puede enviar múltiples bodies.
  • Web en segundo plano: las subidas se detienen si el usuario cierra la pestaña. Usa plataformas nativas si la subida debe continuar con la app en segundo plano.
  • Cancelar: llama a removeUpload({ id }) con el id de startUpload.
  • Progreso: siempre adjunta el events listener antes de empezar, o podrías perder el progreso inicial.

Comienza a subir un archivo a un servidor.

La subida continuará en segundo plano incluso si la app se cierra o pasa a background. Escucha los eventos de upload para trackear el progreso, la finalización o errores.

import { Uploader } from '@capgo/capacitor-uploader';
const { id } = await Uploader.startUpload({
filePath: 'file:///path/to/file.jpg',
serverUrl: 'https://example.com/upload',
headers: {
'Authorization': 'Bearer token'
},
method: 'POST',
uploadType: 'multipart',
fileField: 'photo'
});
console.log('Upload started with ID:', id);

Cancela y elimina una subida en curso.

Esto detendrá la subida si está en progreso y liberará los recursos.

import { Uploader } from '@capgo/capacitor-uploader';
await Uploader.removeUpload({ id: 'upload-123' });

Opciones de configuración para subir un archivo.

export interface uploadOption {
/**
* The local file path of the file to upload.
* Can be a file:// URL or an absolute path.
*
* @since 0.0.1
*/
filePath: string;
/**
* The server URL endpoint where the file should be uploaded.
*
* @since 0.0.1
*/
serverUrl: string;
/**
* The title of the upload notification shown to the user.
* Android only.
*
* @default 'Uploading'
* @since 0.0.1
*/
notificationTitle?: string;
/**
* HTTP headers to send with the upload request.
* Useful for authentication tokens, content types, etc.
*
* @since 0.0.1
* @example
* ```typescript
* headers: {
* 'Authorization': 'Bearer token123',
* 'X-Custom-Header': 'value'
* }
* ```
*/
headers: {
[key: string]: string;
};
/**
* The HTTP method to use for the upload request.
*
* @default 'POST'
* @since 0.0.1
*/
method?: 'PUT' | 'POST';
/**
* The MIME type of the file being uploaded.
* If not specified, the plugin will attempt to determine it automatically.
*
* @since 0.0.1
* @example 'image/jpeg', 'application/pdf', 'video/mp4'
*/
mimeType?: string;
/**
* Additional form parameters to send with the upload request.
* These will be included as form data in multipart uploads.
*
* @since 0.0.1
*/
parameters?: { [key: string]: string };
/**
* The maximum number of times to retry the upload if it fails.
*
* @since 0.0.1
* @default 0
*/
maxRetries?: number;
/**
* 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
*
* @default 'binary'
* @since 0.0.2
*/
uploadType?: 'binary' | 'multipart';
/**
* The form field name for the file when using multipart upload type.
* Only used when uploadType is 'multipart'.
*
* @default 'file'
* @since 0.0.2
*/
fileField?: string;
}

Evento emitido durante el ciclo de vida de la subida.

export interface UploadEvent {
/**
* The current status of the upload.
* - 'uploading': Upload is in progress
* - 'completed': Upload finished successfully
* - 'failed': Upload encountered an error
*
* @since 0.0.1
*/
name: 'uploading' | 'completed' | 'failed';
/**
* Additional data about the upload event.
*
* @since 0.0.1
*/
payload: {
/**
* Upload progress percentage from 0 to 100.
* Only present during 'uploading' events.
*
* @since 0.0.1
*/
percent?: number;
/**
* Error message if the upload failed.
* Only present during 'failed' events.
*
* @since 0.0.1
*/
error?: string;
/**
* HTTP status code returned by the server.
* Present during 'completed' and 'failed' events.
*
* @since 0.0.1
*/
statusCode?: number;
};
/**
* Unique identifier for this upload task.
*
* @since 0.0.1
*/
id: string;
}

Esta página se genera a partir del plugin src/definitions.ts. Vuelve a ejecutar el sync cuando el API público cambie en upstream.

Si estás usando Primeros pasos para planificar las operaciones del dashboard y de API, conéctalo con Uso de @capgo/capacitor-uploader para la capacidad nativa al usar @capgo/capacitor-uploader, Resumen de API para los detalles de implementación en API Overview, Introducción para los detalles de implementación en la Introducción, Claves de API para los detalles de implementación en las claves de API, y Dispositivos para el detalle de implementación en Devices.