A ZIP file is a format that can be used to compress one or more files together at the same location. It helps in reducing the file size and makes it easy to share or transfer the files.
Also, as the data is encrypted in the zip file, the data security is maintained. Whenever you want to send a large batch of files via Email or any other medium, you can overcome the limitation of file size by using a zip file.
Keeping in mind these uses of zip files, I came up with a method to create zip file in Magento 2.
The admin can use the below solutions in various cases like when a customer uploads multiple files from the frontend in case of product customization or personalization. The admin or store designer will have to access these files to implement the personalization that the customer has asked for. In this case, instead of transferring multiple files one by one, the admin can create Magento 2 zip file.
Check the below solution for the same.
Method to create zip file in Magento 2:
You can use any of the below code to create a zip file in Magento 2 as shown below:
public function getZip($source,$destination) { $zip = new \ZipArchive(); $zip->open($destination, \ZipArchive::CREATE); $zip->addFile($source, basename($source)); $zip->close(); return $destination; }
Next, you can call the following function in .phtml file to create a zip file in Magento 2.
getZip('D:\My Folder\download.jpg','D:\zip\Meetanshi.zip')
OR
<?php namespace Vendor\Module\Block; use Magento\Framework\Archive\Zip; protected $zip; public function __construct(Context $context,Zip $zip) { $this->zip = $zip; parent::__construct($context); } public function getZip() { $this->zip->pack('D:\My Folder\download.jpg','D:\zip\Meetanshi.zip'); }
That’s it.
Also, do share the solution with the Magento Community via social media.
Thank you.