Opencart PHP Zip & Download (Ajax Method)


Opencart sayfasındaki bir butona tıklayarak dosyaları indirmek için ajax metodunu kullanabilirsiniz. Bunun için controller ve view dosyalarına ekleyeceğiniz kodlar aşağıdadır.

Controller:
public function downloadAllFiles() {
    $json = array();

    $zip_files = array(
        "file-1.jpg",
        "file-2.jpg",
        "file-3.jpg",
    );
    
    if ( count($zip_files) > 0 ) {
        $zipname = "indir.zip";
        $zip = new ZipArchive;
        $zip->open($_SERVER['DOCUMENT_ROOT']."/store/image/download/".$zipname, ZipArchive::CREATE);
        foreach ($zip_files as $file) {
          $zip->addFile($_SERVER['DOCUMENT_ROOT']."/store/image/download/".$file, $file);
        }
        $zip->close();

        //success and send zip file path
        $json['success'] = 'https://example.com/store/image/download/'.$zipname;
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
    else {
        $json['error'] = "İndirilecek dosya bulunamadı! Lütfen kontrol ediniz.";
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

View:
<!-- Add Download Button -->
<button id="btn-download-zip" data-loading-text="<?php echo $text_downloading; ?>" class="btn btn-info"><?php echo $text_download; ?> <i class="fa fa-download"></i></button>

<!-- Add Ajax Script -->
<script type="text/javascript">
    $(document).delegate('#btn-download-zip', 'click', function() {
        $.ajax({
            url: 'index.php?route=sale/order/downloadallfiles',
            type: 'post',
            dataType: 'json',
            beforeSend: function() {
                $('#btn-download-zip').button('loading');
            },
            complete: function() {
                $('#btn-download-zip').button('reset');
            },
            success: function(json) {
                $('.alert').remove();

                if (json['error']) {
                    $('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
                }
                else {
                    //download zip file
                    window.location.href = json['success'];
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    });
</script>

Yorumlar