I want to create and download zip of a folder in my custom module.
I followed this link, but getting fatal error Uncaught Error: Class 'Vendor\Module\Controller\Custom\ZipArchive' not found.
How to accomplish this. please help.
You can create a model file in your module.
File: MageExt/Download/Model/CustomDownload.php
<?php
namespace MageExt\Download\Model;
class CustomDownload
{
protected $directoryList;
protected $driver;
protected $fileFactory;
public function __construct(
\Magento\Framework\App\Filesystem\DirectoryList $directoryList,
\Magento\Framework\Shell\Driver $driver,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory
)
{
$this->directoryList = $directoryList;
$this->driver = $driver;
$this->fileFactory = $fileFactory;
}
public function downloadCustomDocs()
{
if (!class_exists('\ZipArchive')) {
die('ZipArchive class not found');
}
$dir = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::ROOT);
//chdir($dir.'/app/code/CustomDocs');
$rootPath = $dir.'/app/code/CustomDocs';
chdir($rootPath);
//$this->driver->execute('zip -r ../CustomDocs.zip *', []);
$zip = new \ZipArchive();
$zip->open('CustomDocs.zip', \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
$this->fileFactory->create(
'CustomDocs.zip',
[
'type' => 'filename',
'value' => $dir.'/app/code/CustomDocs/CustomDocs.zip',
'rm' => true
],
\Magento\Framework\App\Filesystem\DirectoryList::ROOT,
'application/zip'
);
}
}
Now you can call downloadCustomDocs() function from anywhere in your module.
-
can you please explain it by adding comments. i am getting cofused. – iqbal malik Feb 14 '19 at 12:18
-
Tell me the Vendor name, Module name and folder to zip inside your module .. – Yash Shah Feb 14 '19 at 12:23
-
Vendor: MageExt, Module: Download. But the folder needs to download is in app/code directory, which is parallel to the module directory. The name of directory is "CustomDocs", – iqbal malik Feb 14 '19 at 12:25
-
Let me know the folder path including name of the folder which you want to download. – Yash Shah Feb 14 '19 at 12:26
-
Whenever there is any structural (class added or class name/reference modified) in your modeule: Or Any JS/Less file contents change in your theme: You need to build your static content again and setup compile again as well. (There is a set of commands for this already)
Otherwise your changes will not be picked..
new \ZipArchive()
– kunj Feb 14 '19 at 10:35