Ajit Kumar Thakur
Ajit Kumar Thakur

Reputation: 35

Download product images in a zip on click of download button in magento

I have a custom page for specific products of a category.

here is the link and code by which I am showing all the images only.

<div style="float:left; width:100%;">
    <?php $_helper = $this->helper('catalog/output'); ?>
    <?php $product = $this->getProduct(); ?>
    <?php foreach ($product->getMediaGalleryImages() as $image) :?>

        <div style="width: 48%; margin:1%;float:left">
            <img width="100%;" src="<?php echo Mage::helper('catalog/image')->init($product, 'image', $image->getFile()); ?>" alt="<?php echo $product->getName()?>" />
        </div>

    <?php endforeach; ?>

</div>
<div style="float:left; width:100%;">
    <button type="button" style="display:block;margin:0 auto;">Download</button>
</div>

Now I need to download all the images of product on click of the button, the link is http://thevastrafashion.com/english/testing-1.html How can I achieve this. If you want anything more please leave a comment.

Upvotes: 0

Views: 2665

Answers (1)

You can do following to achieve this.

foreach ($sku as $key => $value) {
    $productId = $value;
    $products = Mage::getModel('catalog/product')->loadByAttribute('sku', $productId);
    $inStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($products)->getIsInStock();
    if($inStock)
    {
        array_push($file_arr, (string) Mage::helper('catalog/image')->init($products, 'image'));
    }
}
if(count($file_arr)>0)
{
    $result = create_zip($file_arr);
}

function create_zip($files = array()) {
    try{
    $zip = new ZipArchive();
    $tmp_file = tempnam('.', '');
    $zip->open($tmp_file, ZipArchive::CREATE);
    foreach ($files as $file) {
        $download_file = file_get_contents($file);
        $zip->addFromString(basename($file), $download_file);
    }
    $zip->close();
    header('Content-disposition: attachment; filename=download.zip');
    header('Content-type: application/zip');
    header("Accept-Ranges: bytes");
    header("Pragma: public");
    header("Expires: -1");
    header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0"); 
    header('Content-Length: ' . filesize($tmp_file));
    $chunksize = 8 * (1024 * 1024); //8MB (highest possible fread length)
          $handle = fopen($tmp_file, 'rb');
          $buffer = '';
          while (!feof($handle) && (connection_status() === CONNECTION_NORMAL)) 
          {
            $buffer = fread($handle, $chunksize);
            print $buffer;
            ob_flush();
            flush();
          }
          if(connection_status() !== CONNECTION_NORMAL)
          {
            echo "Connection aborted";
          }
          fclose($handle);
    }
    catch(Exception $e)
    {
        Mage::log($e,null,'download_error.log');
    }
}

This is reference code only. So you need to change according to your requirement.

Upvotes: 3

Related Questions