Zum Inhalt springen

Erste Schritte

  1. Paket installieren

    Terminal-Fenster
    npm i @capgo/capacitor-zip
  2. Mit nativen Projekten synchronisieren

    Terminal-Fenster
    npx cap sync

Importieren Sie das Plugin und komprimieren oder entpacken Sie die Dateien:

import { CapacitorZip } from '@capgo/capacitor-zip';
// Zip a folder
const zipFolder = async () => {
await CapacitorZip.zip({
source: 'file:///path/to/folder',
destination: 'file:///path/to/archive.zip'
});
console.log('Folder zipped successfully!');
};
// Unzip an archive
const unzipArchive = async () => {
await CapacitorZip.unzip({
source: 'file:///path/to/archive.zip',
destination: 'file:///path/to/output/folder'
});
console.log('Archive extracted successfully!');
};

Erstellt ein ZIP-Archiv aus einem Quellordner.

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'
});

Extrahiert Dateien aus einem ZIP-Archiv.

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;
}
}
}

Erstellen von Archiven mit Fortschrittsverfolgung

Section titled “Erstellen von Archiven mit Fortschrittsverfolgung”
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;
}
};
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;
};
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;
}
};
  1. Pfadvalidierung: Validieren Sie immer Quell- und Zielpfade vor Vorgängen
  2. Fehlerbehandlung: Wickeln Sie alle Zip-/Unzip-Vorgänge in Try-Catch-Blöcke ein
  3. Bereinigung: Entfernen Sie temporäre Dateien und Ordner nach den Vorgängen
  4. Große Dateien: Seien Sie vorsichtig bei großen Archiven auf Mobilgeräten
  5. Berechtigungen: Stellen Sie sicher, dass Ihre App über die erforderlichen Dateisystemberechtigungen verfügt

Zip-Vorgang schlägt fehl: Stellen Sie sicher, dass der Quellpfad vorhanden und zugänglich ist Entpacken schlägt fehl: Überprüfen Sie, ob die ZIP-Datei gültig ist und der Zielpfad beschreibbar ist Nicht genügend Speicherplatz: Überwachen Sie den verfügbaren Speicherplatz vor dem Betrieb Berechtigung verweigert: Überprüfen Sie die Dateisystemberechtigungen in Ihrer App-Konfiguration