【问题标题】:Yii2 file download using custom componentsYii2 文件下载使用自定义组件
【发布时间】:2017-01-15 03:47:30
【问题描述】:

在 yii2 项目中,我使用组件来下载路径保存在我的数据库中的文件。

我已经在我的操作栏中设置了下载按钮

['class' => 'yii\grid\ActionColumn',
                'template'=>'{update}{pdf}{delete}',
                'buttons'=>[
                    // to display pdf icon.
                   'pdf' => function ($url, $model) {    
                                $id = [];
                                foreach ($model->sdsrefs as $mod)
                                    $id[] = $mod->file_id;
                                    return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', Url::to(['product/download', 'id' => implode($id)]), [

                                   ]);                      
                            }
                ],
                'options'=>[
                    'style'=>'width:70px;'
                ]
  ],

我已经在上面的代码中设置了控制器动作的链接。

我的控制器操作

public function actionDownload($id)
    {
        Yii::$app->files->downloadFile($id);
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }

在控制器操作中,我调用组件以进行下载。当我单击 PDF 按钮时,这里发生的事情不是下载,而是回显页面中的内容。当我按下 Pdf 按钮时,我希望它执行文件下载。

我在组件中的下载功能。

 public static function downloadFile($id) {
        $file = File::findOne($id);
        $filepath = Files::getFilePath($id);
        if (file_exists($filepath)) {
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.$file->file_name);
            header('Content-Length: ' . filesize($filepath));
            readfile("$filepath");
        }else{
            echo "file not exist: ".$filepath;            
        }
        exit;
    }

当我点击 pdf 操作按钮时,我怎样才能实现我的结果。即下载?

谢谢

【问题讨论】:

    标签: download controller routes yii2 components


    【解决方案1】:

    为什么不使用 Response 对象的 sendFile() 方法?

    return Yii::$app->response->sendFile($pathFile, $filename);
    

    查看文档:http://www.yiiframework.com/doc-2.0/yii-web-response.html#sendFile()-detail

    【讨论】:

    • 文件路径已经在我们的项目中实现了。所以我们需要使用组件的设置文件路径和下载选项
    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    相关资源
    最近更新 更多