duanlei5339 2017-05-04 12:59
浏览 120

Yii2 Ajax请求文件下载

In my Yii2 application i'm dynamically generating .zip files that i want to download through an Ajax call in one of my views.

This is my code

_view.php

$js = <<<JS
    $('#button-download').on('click', function(){

        var tkn = $('meta[name="csrf-token"]').attr("content");
        var fields =  JSON.stringify($('#gridview').yiiGridView('getSelectedRows'));

        $.ajax({
            url: '$urlDownload', // Generated with Url::toRoute([someaction]);
            type: 'get',
            dataType: 'json',
            data: {
                field: fields,
                _csrf : tkn, 
            },
            success: function(data){
                console.log(data);
                // ?
                // ?
                // ?
            }
        });
    });
JS;

$this->registerJs($js);

This is my view file, here i register the $.ajax method that reach an action in my controller.

Controller.php

/**
 * Download Action
 * 
 * @param integer $field
 * @return mixed
 */
public function actionDownload($field) {

    if (Yii::$app->request->isAjax && !empty(json_decode($field))) {

        // Bring some Data From Db

        // Create a new Zip
        $archive = new \ZipArchive();
        $now = $timestamp; // let's assume that the $now variable is a valid timestamp

        $zip_name = Yii::t('app', 'NameThisArchive').$now.'.zip';

        if (!$archive->open(Yii::getAlias('@app/runtime/foo').'/'.$zip_name, \ZipArchive::CREATE)) {
            throw new \Exception('Can\'t create the file');
        }

        foreach ($datafromdb as $record) {

            if ($somecondiction) {

                // Generating files and adding them to my archive

                $archive->addFile($path, '/'.Yii::t('app', 'somefileinpdf{0}.pdf', [$record->id]));
            }
        }
        $archive->close();

        // return ?
        // Yii::$app->response->sendFile($path, $zip_name);

    }
}

In this controller i receive the data from the ajax request. I'm able to create the zip archive and save it to my runtime folder.

Now, the problem, is how can i send this file to the ajax call. (in the .success() callback).

What should i return ?

Looking in the yii official forum i've found some response helper:

Yii::$app->response->sendFile("path", "Filename");

If I return that function return Yii::$app->response->sendFile("path", "Filename");

No file is download in my browser. But looking in my Safari browser console i see that a xhr request (the one i send with ajax) return some data.

So a response is given. How can i capture it with my Ajax function?

Thanks for any help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 求图像处理的matlab方案
    • ¥50 winform中使用edge的Kiosk模式
    • ¥15 关于#python#的问题:功能监听网页
    • ¥15 怎么让wx群机器人发送音乐
    • ¥15 fesafe材料库问题
    • ¥35 beats蓝牙耳机怎么查看日志
    • ¥15 Fluent齿轮搅油
    • ¥15 八爪鱼爬数据为什么自己停了
    • ¥15 交替优化波束形成和ris反射角使保密速率最大化
    • ¥15 树莓派与pix飞控通信