79 lines
2.6 KiB
Dart
79 lines
2.6 KiB
Dart
import 'dart:io';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:archive/archive_io.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:path/path.dart' as p;
|
|
|
|
/// A dedicated service to handle the creation of ZIP archives for FTP submission.
|
|
class ZippingService {
|
|
/// Creates multiple JSON files from a map of data and zips them into a single archive.
|
|
/// The map keys will be the filenames (e.g., 'db.json', 'form_data.json').
|
|
/// The map values should be the JSON string content for each file.
|
|
Future<File?> createDataZip({
|
|
required Map<String, String> jsonDataMap,
|
|
required String baseFileName,
|
|
}) async {
|
|
try {
|
|
final tempDir = await getTemporaryDirectory();
|
|
final zipFilePath = p.join(tempDir.path, '$baseFileName.zip');
|
|
final encoder = ZipFileEncoder();
|
|
encoder.create(zipFilePath);
|
|
|
|
debugPrint("Creating data ZIP at: $zipFilePath");
|
|
|
|
for (var entry in jsonDataMap.entries) {
|
|
final fileName = entry.key;
|
|
final jsonContent = entry.value;
|
|
|
|
// --- MODIFIED: The codeUnits property is already a List<int>. No need to wrap it in a Stream. ---
|
|
final archiveFile = ArchiveFile(fileName, jsonContent.length, jsonContent.codeUnits);
|
|
encoder.addArchiveFile(archiveFile);
|
|
|
|
debugPrint("Added $fileName to data ZIP.");
|
|
}
|
|
|
|
encoder.close();
|
|
debugPrint("Data ZIP creation complete.");
|
|
return File(zipFilePath);
|
|
} catch (e) {
|
|
debugPrint("Error creating data ZIP file: $e");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// Creates a ZIP file from a list of image files.
|
|
Future<File?> createImageZip({
|
|
required List<File> imageFiles,
|
|
required String baseFileName,
|
|
}) async {
|
|
if (imageFiles.isEmpty) {
|
|
debugPrint("No images provided to create an image ZIP.");
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
final tempDir = await getTemporaryDirectory();
|
|
final zipFilePath = p.join(tempDir.path, '${baseFileName}_img.zip');
|
|
final encoder = ZipFileEncoder();
|
|
encoder.create(zipFilePath);
|
|
|
|
debugPrint("Creating image ZIP at: $zipFilePath");
|
|
|
|
for (var imageFile in imageFiles) {
|
|
if (await imageFile.exists()) {
|
|
await encoder.addFile(imageFile);
|
|
debugPrint("Added ${p.basename(imageFile.path)} to image ZIP.");
|
|
} else {
|
|
debugPrint("Skipping non-existent file: ${imageFile.path}");
|
|
}
|
|
}
|
|
|
|
encoder.close();
|
|
debugPrint("Image ZIP creation complete.");
|
|
return File(zipFilePath);
|
|
} catch (e) {
|
|
debugPrint("Error creating image ZIP file: $e");
|
|
return null;
|
|
}
|
|
}
|
|
} |