入门
Copy a setup prompt with the install steps and the full markdown guide for this plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-zip`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/zh/docs/plugins/zip/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
-
安装软件包
Terminal window npm i @capgo/capacitor-zipTerminal window pnpm add @capgo/capacitor-zipTerminal window yarn add @capgo/capacitor-zipTerminal window bun add @capgo/capacitor-zip -
与原生项目同步
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
导入插件并压缩或解压缩文件:
import { CapacitorZip } from '@capgo/capacitor-zip';
// Zip a folderconst zipFolder = async () => { await CapacitorZip.zip({ source: 'file:///path/to/folder', destination: 'file:///path/to/archive.zip' }); console.log('Folder zipped successfully!');};
// Unzip an archiveconst unzipArchive = async () => { await CapacitorZip.unzip({ source: 'file:///path/to/archive.zip', destination: 'file:///path/to/output/folder' }); console.log('Archive extracted successfully!');};API 参考
Section titled “API 参考”zip(选项)
Section titled “zip(选项)”从源文件夹创建 ZIP 存档。
interface ZipOptions { source: string; // Path to folder to compress destination: string; // Path for output ZIP file}
await CapacitorZip.zip({ source: 'file:///path/to/folder', destination: 'file:///path/to/archive.zip'});解压(选项)
Section titled “解压(选项)”从 ZIP 存档中提取文件。
interface UnzipOptions { source: string; // Path to ZIP file destination: string; // Path to extract to}
await CapacitorZip.unzip({ source: 'file:///path/to/archive.zip', destination: 'file:///path/to/output/folder'});import { CapacitorZip } from '@capgo/capacitor-zip';import { Filesystem, Directory } from '@capacitor/filesystem';
export class ZipService { async createBackup() { try { const timestamp = Date.now(); const sourceDir = `${Filesystem.Directory.Data}/userdata`; const destPath = `${Filesystem.Directory.Documents}/backup_${timestamp}.zip`;
await CapacitorZip.zip({ source: sourceDir, destination: destPath });
console.log('Backup created:', destPath); return destPath; } catch (error) { console.error('Backup failed:', error); throw error; } }
async restoreBackup(backupPath: string) { try { const destDir = `${Filesystem.Directory.Data}/userdata`;
// Clear existing data await Filesystem.rmdir({ path: 'userdata', directory: Directory.Data, recursive: true });
// Extract backup await CapacitorZip.unzip({ source: backupPath, destination: destDir });
console.log('Backup restored successfully'); } catch (error) { console.error('Restore failed:', error); throw error; } }
async compressFiles(filePaths: string[], outputPath: string) { try { // Create temporary directory const tempDir = `${Filesystem.Directory.Cache}/temp_zip_${Date.now()}`;
await Filesystem.mkdir({ path: tempDir, directory: Directory.Cache, recursive: true });
// Copy files to temp directory for (const filePath of filePaths) { const fileName = filePath.split('/').pop(); await Filesystem.copy({ from: filePath, to: `${tempDir}/${fileName}` }); }
// Zip the temp directory await CapacitorZip.zip({ source: tempDir, destination: outputPath });
// Clean up temp directory await Filesystem.rmdir({ path: tempDir, directory: Directory.Cache, recursive: true });
return outputPath; } catch (error) { console.error('Compression failed:', error); throw error; } }
async extractSpecificFiles(zipPath: string, fileNames: string[]) { try { // Extract to temp location const tempDir = `${Filesystem.Directory.Cache}/temp_extract_${Date.now()}`;
await CapacitorZip.unzip({ source: zipPath, destination: tempDir });
// Read only specific files const extractedFiles: { [key: string]: string } = {};
for (const fileName of fileNames) { const content = await Filesystem.readFile({ path: `${tempDir}/${fileName}`, directory: Directory.Cache }); extractedFiles[fileName] = content.data; }
// Clean up await Filesystem.rmdir({ path: tempDir, directory: Directory.Cache, recursive: true });
return extractedFiles; } catch (error) { console.error('Extraction failed:', error); throw error; } }}通过进度跟踪创建档案
Section titled “通过进度跟踪创建档案”const zipWithProgress = async (source: string, destination: string) => { console.log('Starting compression...');
try { await CapacitorZip.zip({ source, destination }); console.log('Compression complete!'); } catch (error) { console.error('Compression failed:', error); throw error; }};批量存档操作
Section titled “批量存档操作”const batchZip = async (folders: string[]) => { const results = [];
for (const folder of folders) { const folderName = folder.split('/').pop(); const zipPath = `${folder}_${Date.now()}.zip`;
try { await CapacitorZip.zip({ source: folder, destination: zipPath }); results.push({ folder, zipPath, success: true }); } catch (error) { results.push({ folder, error, success: false }); } }
return results;};安全档案创建
Section titled “安全档案创建”const createSecureBackup = async (dataPath: string) => { // Zip the data const zipPath = `${Filesystem.Directory.Documents}/secure_backup.zip`;
await CapacitorZip.zip({ source: dataPath, destination: zipPath });
// Optionally encrypt the zip file here using a crypto plugin
return zipPath;};const validateArchive = async (zipPath: string): Promise<boolean> => { try { const tempDir = `${Filesystem.Directory.Cache}/validate_${Date.now()}`;
// Try to extract await CapacitorZip.unzip({ source: zipPath, destination: tempDir });
// Clean up await Filesystem.rmdir({ path: tempDir, directory: Directory.Cache, recursive: true });
return true; } catch (error) { console.error('Archive validation failed:', error); return false; }};- 路径验证:在操作之前始终验证源路径和目标路径
- 错误处理:将所有zip/unzip操作包装在try-catch块中
- 清理:删除操作后的临时文件和文件夹
- 大文件:谨慎对待移动设备上的大档案
- 权限:确保您的应用程序具有必要的文件系统权限
Zip 操作失败:确保源路径存在且可访问 解压缩失败:检查 ZIP 文件是否有效且目标路径是否可写 存储不足:在操作之前监视可用磁盘空间 权限被拒绝:验证应用程序配置中的文件系统权限