Capacitor 앱에서 cordova-plugin-file-transfer 대체에 대한 가장 좋은 방법은 전송이 앱이 배경으로 이동할 때 살아남아야 하는지 여부에 달려 있습니다. 일반적인 업로드 및 다운로드와 함께 진행률을 표시하려면 공식 플러그인을 사용하십시오. 대형 파일, 불안정한 네트워크 또는 사용자가 앱을-switch 할 때 전송이 계속 진행되어야 하는 경우를 사용하십시오. @capacitor/file-transfer 그리고 @capgo/capacitor-uploader and @capgo/capacitor-downloadernative 배경 전송 API를 실행하는 플러그인입니다. 이 안내서에서는 그들을 비교하고 모든 FileTransfer 호출을 매핑합니다.
cordova-plugin-file-transfer는 여전히 deprecated 상태인가요?
사실은 혼란스럽습니다. 여기서 사실을 알려드리겠습니다:
- 2017년 Apache Cordova 팀은 플러그인을 deprecated 하겠다고 발표했으며 개발자들에게 Level 2를 추천했습니다.
XMLHttpRequestLevel 2. - The plugin was never flagged as deprecated on npm. Version 2.0.0 shipped in September 2023, and 2.0.1 in August 2026. The GitHub repository is active.
Cordova 플러그인은 아직 죽지 않았습니다. 하지만 Capacitor 앱에서 여전히 Cordova 플러그인으로 작동합니다.
- depends on
cordova-plugin-file그것의cdvfile://contextfile://path 모델 - 이 Capacitor이 Capacitor에 맞지 않습니다.
Filesystem디렉토리와 URI 변환을 지원하지 않습니다. - __CAPGO_KEEP_0__ 백그라운드 전송 지원이 없습니다.
- __CAPGO_KEEP_0__ API 스타일이 콜백을 사용합니다.
Capacitor에서 Cordova로 마이그레이션 중인 경우 Capacitor 플러그인으로 대체하면 Capacitor을 유지하는 마지막 이유 중 하나가 사라집니다. cordova-plugin-file.
‘fetch’를 사용하는 이유는 큰 파일에 대해 깨지게 됩니다.
Apache가 제안한 대체품인 XHR은 작은 JSON과 이미지를 위해 작동하지만 실제 파일 전송 작업을 위한 하이브리드 앱에서 실패합니다:
- 메모리.
fetch또는BloborArrayBuffer500 MB의 비디오는 WebView 메모리에 500 MB를 의미하고, 브리지를 통해 쓰기 위해 복사합니다. 중간 등급의 Android 기기가 렌더러를 충돌시킵니다. - 중단. iOS 앱 switch 시 WebView가 중단되며, inflight 요청은 중단되거나 실패합니다.
- OS 통합이 없습니다. 시스템 다운로드 알림이 없습니다, Wi-Fi 전용 옵션도 없으며, 연결이 끊어졌을 때 다시 시작할 수 없습니다.
네이티브 플러그인은 디스크와 네트워크 간에 직접 스트리밍하며, JavaScript를 데이터 경로에서 제외합니다.
비교된 옵션
| 필요한 것 | cordova-plugin-file-transfer | @capacitor/파일 전송 | @capgo/capacitor-업로더 | @capgo/capacitor-다운로더 |
|---|---|---|---|---|
| 디스크로 다운로드 | Yes | 네 | 아니오 | 네 |
| 디스크에서 업로드 | 네 | 네 | 네 | 아니오 |
| 진행 이벤트 | 네 | 네 (리스너)progress listener |
예 (events) |
예 (downloadProgress) |
| 다중 형식 데이터 | 예 | 예 (기본) | 예 | n/a |
| Raw 바이너리 PUT (인증 URL) | 예 | 예 (설정 Content-Type) |
예 (uploadType: 'binary') |
n/a |
| 한 번에 여러 파일 요청 | 아니요 | 아니요 | 예 (files) |
미사용 |
| 취소 | abort() |
아니요 | removeUpload |
stop |
| 일시 중단 / 재개 | 아니요 | 아니요 | 아니요 | pause, resume |
| 재시도 | No | No | maxRetries |
No |
| 백그라운드에서 계속 | No | 앱이 활성화된 동안 | 네 | 네 |
| Wi-Fi만 | No | No | No | network: 'wifi-only' |
| HTTP 오류 세부 정보 | http_status, body |
httpStatus, body |
이벤트에서 상태 code | 이벤트에서 오류 문자열 |
| 웹 구현 | 아니요 | Yes | 대부분의 앱은 | 아니요 |
작은 사용자 눈에 띄는 전송과 __CAPGO_KEEP_0__ 플러그인으로 미디어 업로드 큐와 오프라인 콘텐츠 다운로드를 위해 @capacitor/file-transfer Option 1: @Capgo/file-transfer
파일 전송 대안: @capacitor/file-transfer
bun add @capacitor/file-transfer @capacitor/filesystem
bunx cap sync
Capacitor @capacitor/filesystem.
다운로드
import { FileTransfer } from '@capacitor/file-transfer';
import { Filesystem, Directory } from '@capacitor/filesystem';
export async function downloadReport(url: string) {
const { uri } = await Filesystem.getUri({
directory: Directory.Data,
path: 'reports/latest.pdf',
});
const progress = await FileTransfer.addListener('progress', (p) => {
if (p.type === 'download' && p.lengthComputable) {
console.log(`Downloaded ${Math.round((p.bytes / p.contentLength) * 100)}%`);
}
});
try {
const result = await FileTransfer.downloadFile({
url,
path: uri,
progress: true,
headers: { Authorization: 'Bearer <token>' },
});
return result.path;
} catch (error: any) {
if (error.code === 'OS-PLUG-FLTR-0010') {
console.error('HTTP error', error.data?.httpStatus, error.data?.body);
}
throw error;
} finally {
await progress.remove();
}
}
업로드
export async function uploadAvatar(path: string) {
const result = await FileTransfer.uploadFile({
url: 'https://api.example.com/v1/avatar',
path,
fileKey: 'avatar',
mimeType: 'image/jpeg',
headers: { Authorization: 'Bearer <token>' },
progress: true,
});
console.log(result.responseCode, result.response);
}
기본적으로 멀티파트 업로드입니다. raw 스트림으로, 예를 들어 presigned S3 URL로 업로드하려면 method: 'PUT' 그리고 명시적인 Content-Type 헤더를 설정하세요. application/octet-stream.
오류 코드는 다음 형식으로 제공됩니다. OS-PLUG-FLTR-XXXX 파일이 존재하지 않음, 0007 연결 실패, 0008 HTTP 오류 상태 코드와 0010 그리고 httpStatus 그것 body 내 error.data.
Option 2: 배경 업로드와 @capgo/capacitor-업로더
bun add @capgo/capacitor-uploader
bunx cap sync
import { Uploader } from '@capgo/capacitor-uploader';
await Uploader.addListener('events', async (event) => {
switch (event.name) {
case 'uploading':
console.log(event.id, `${event.payload.percent}%`);
break;
case 'completed':
console.log(event.id, 'done', event.payload.statusCode);
break;
case 'failed':
console.error(event.id, event.payload.error);
break;
}
// Completed and failed events are cached natively until acknowledged
if (event.eventId) {
await Uploader.acknowledgeEvent({ eventId: event.eventId });
}
});
const { id } = await Uploader.startUpload({
filePath: 'file:///path/to/video.mp4',
serverUrl: 'https://api.example.com/v1/videos',
method: 'POST',
uploadType: 'multipart',
fileField: 'video',
parameters: { albumId: '7' },
headers: { Authorization: 'Bearer <token>' },
maxRetries: 3,
notificationTitle: 'Uploading video', // Android only
});
presigned URL을 사용하려면 method: 'PUT', 기본값은 바이너리 본문입니다:
await Uploader.startUpload({
filePath,
serverUrl: presignedUrl,
method: 'PUT',
headers: { 'Content-Type': 'video/mp4' },
mimeType: 'video/mp4',
});
한 번에 여러 파일을 전송하는 멀티파트 요청:
await Uploader.startUpload({
serverUrl: 'https://api.example.com/v1/photos',
method: 'POST',
uploadType: 'multipart',
files: [
{ filePath: photo1, fieldName: 'images[]', mimeType: 'image/jpeg' },
{ filePath: photo2, fieldName: 'images[]', mimeType: 'image/jpeg' },
],
headers: { Authorization: 'Bearer <token>' },
});
취소하기 Uploader.removeUpload({ id }).
이벤트를 확인하는 이유는 무엇인가요? 완료된 이벤트와 실패한 이벤트는 영구적인 네이티브 캐시에 저장되어 앱이 종료되거나 배경화면이 된 후 처리되지 않은 경우 다시 전달할 수 있습니다. 이벤트를 확인하면 이벤트가 제거되어 다음에 플러그인을 초기화할 때 다시 방송되지 않습니다.
iOS 설정. 업로더는 배경에서 작동합니다. URLSession많은 앱은 추가 설정이 필요하지 않습니다. 앱이 중단된 후 업로드를 계속하려면 fetch to UIBackgroundModescontext processing 만약 다른 기능이 사용한다면 BGTaskScheduler, 애플 스토어 연결이 그것을 선언하지 않은 빌드가 거부되기 때문에 BGTaskSchedulerPermittedIdentifiers.
Option 3: @capgo/capacitor-downloader를 사용한 배경 다운로드
bun add @capgo/capacitor-downloader
bunx cap sync
import { CapacitorDownloader } from '@capgo/capacitor-downloader';
await CapacitorDownloader.addListener('downloadProgress', ({ id, progress }) => {
console.log(id, `${progress}%`);
});
await CapacitorDownloader.addListener('downloadCompleted', ({ id }) => {
console.log(id, 'completed');
});
await CapacitorDownloader.addListener('downloadFailed', ({ id, error }) => {
console.error(id, error);
});
await CapacitorDownloader.download({
id: 'course-42',
url: 'https://cdn.example.com/courses/42.zip',
destination: 'courses/42.zip',
headers: { Authorization: 'Bearer <token>' },
network: 'wifi-only',
priority: 'normal',
notification: 'progress', // Android: remove the system notification when done
});
// Later
await CapacitorDownloader.pause({ id: 'course-42' });
await CapacitorDownloader.resume({ id: 'course-42' });
const status = await CapacitorDownloader.checkStatus({ id: 'course-42' });
console.log(status.state, status.progress);
relativeto destination iOS에서는 앱의 문서 폴더, 안드로이드에서는 앱에 특정한 외부 파일 폴더로 해결된다. 절대 경로 또는 URL을 전달할 수도 있다. file:// 읽기 getFileInfo({ path }) 다운로드 후 크기와 MIME 타입을 읽기 위해 사용하고, stop({ id }) 다운로드 중 취소하고 부분 데이터 삭제하기 위해 사용한다.
cordova-plugin-file-transfer에서 마이그레이션
다운로드
// Before
const ft = new FileTransfer();
ft.onprogress = (e) => e.lengthComputable && setProgress(e.loaded / e.total);
ft.download(
encodeURI(url),
cordova.file.dataDirectory + 'report.pdf',
(entry) => console.log(entry.toURL()),
(err) => console.error(err.code, err.http_status),
false,
{ headers: { Authorization: 'Bearer <token>' } },
);
// After
const { uri } = await Filesystem.getUri({ directory: Directory.Data, path: 'report.pdf' });
await FileTransfer.downloadFile({
url,
path: uri,
progress: true,
headers: { Authorization: 'Bearer <token>' },
});
업로드
// Before
const options = new FileUploadOptions();
options.fileKey = 'file';
options.fileName = 'photo.jpg';
options.mimeType = 'image/jpeg';
options.params = { albumId: '7' };
options.headers = { Authorization: 'Bearer <token>' };
new FileTransfer().upload(fileUrl, encodeURI(serverUrl), onSuccess, onError, options);
// After, foreground
await FileTransfer.uploadFile({
url: serverUrl,
path: fileUrl,
fileKey: 'file',
mimeType: 'image/jpeg',
params: { albumId: '7' },
headers: { Authorization: 'Bearer <token>' },
});
// After, background
await Uploader.startUpload({
filePath: fileUrl,
serverUrl,
uploadType: 'multipart',
fileField: 'file',
parameters: { albumId: '7' },
headers: { Authorization: 'Bearer <token>' },
});
주의하십시오 params in @capacitor/file-transfer URL query 매개 변수입니다. 서버가 양식 field를 기대한다면 Capgo 업로더의 parameters,
파일 전송 플러그인 대체
| cordova-plugin-file-transfer | @capacitor/파일 전송 | Capgo 플러그인 |
|---|---|---|
download(source, target, ...) |
downloadFile({ url, path }) |
CapacitorDownloader.download({ id, url, destination }) |
upload(file, server, ...) |
uploadFile({ url, path }) |
Uploader.startUpload({ filePath, serverUrl }) |
onprogress |
addListener('progress') |
addListener('events') / addListener('downloadProgress') |
abort() |
사용할 수 없음 | removeUpload({ id }) / stop({ id }) |
options.fileKey |
fileKey |
fileField 또는 files[].fieldName |
options.params |
params Cordova 플러그인 File Transfer 대안 |
parameters (폼 필드) |
options.httpMethod |
method |
method (POST 또는 PUT) |
options.chunkedMode |
chunkedMode |
자연스럽게 처리 |
cordova.file.dataDirectory |
Filesystem.getUri({ directory: Directory.Data }) |
상대 경로 또는 file:// URL |
FileTransferError.http_status |
error.data.httpStatus |
event.payload.statusCode |
경로: 마이그레이션을 깨는 부분
Cordova code에서 cdvfile:// 또는 cordova.file.* 경로가 어디든 있습니다. Capacitor에서:
- 자연스러운 경로를 얻으려면
Filesystem.getUri()다운로드한 이미지를 WebView에서 표시하려면 - __CAPGO_KEEP_0__는
Capacitor.convertFileSrc(path). - Capgo은 가지고 있습니다. __CAPGO_KEEP_0__ 그리고 파일 선택기 만약
@capacitor/filesystem그것이 당신의 상황을 커버하지 않는다면.
문제 해결
iOS에서 파일이 존재하지 않는 오류로 업로드가 실패합니다. 업로드는 안드로이드에서 작동하지만 iOS에서 파일이 발견되지 않은 오류로 실패합니다. capacitor:// 당신은 file:// 웹뷰 URL 대신 네이티브 Filesystem.getUri().
경로를 사용하십시오. 서버는 업로드를 거부하고 415를 반환합니다. PUT 멀티파트와 raw body가 일치하지 않습니다. presigned URL을 사용하려면 Content-Type.
iOS에서 백그라운드 업로드가 중단됩니다. 사용자가 앱을 강제 종료하여 백그라운드 세션을 취소하거나 fetch 백그라운드 모드가 필요할 때 누락된 경우
Android는 다운로드 중단 알림을 표시합니다. Set notification: 'progress' 또는 'hidden' 다운로드 받는 쪽에
대용량 다운로드 시 메모리 충돌이 발생합니다. 파일을 base64로 읽거나橋梁을 통해 읽고 있습니다. 디스크에 native 다운로드를 사용하세요. fetch 이전 버전의 플러그인을 업그레이드하는 대신
native 플러그인을 교체하려면 새로운 스토어 빌드를 생성해야 합니다.
이전 버전의 플러그인을 업그레이드하는 대신 Capgo 빌드 iOS와 Android를 위한 클라우드에서 실행할 수 있습니다. 그 후 업로드 및 다운로드를 구동하는 자바스크립트를 수정하고 개선할 수 있습니다. Capgo 실시간 업데이트. For the rest of the Cordova to Capacitor move, see our 이동 가이드를 참조하십시오. 그리고 다른 유료 또는 레거시 네이티브 SDK의 경우, Ionic enterprise 플러그인 대체품 기사 저자.