Compress and Extract Zip Files in Apex
Salesforce now offers a native Apex Zip library with the Compression namespace, making it easier than ever to compress and extract files in Apex.
Key Features:
- Create and extract Zip files natively in Apex.
- Optimise compression with different methods and levels.
- Extract specific files from a Zip archive without decompressing everything.
How To Use It:
Compress multiple attachments into a Zip file:
Compression.ZipWriter writer = new Compression.
ZipWriter();List contentDocumentIds = new List();// Add IDs of documents to be compressed to contentDocumentIdsfor ( ContentVersion cv : [SELECT PathOnClient, VersiondataFROM ContentVersionWHERE ContentDocumentId IN :contentDocumentIds]){writer.addEntry(cv.PathOnClient, cv.versiondata);}blob zipAttachment = writer.getArchive();
Extract specific files from a Zip archive:Compression.
ZipReader reader = new Compression.ZipReader(translationZip);
ZipEntry frTranslation = reader.getEntry(‘translations/fr.json’);
Blob frTranslationData = reader.extractEntry(frTranslation);Available in: All editions.