controller - Yii2 file download using custom components -


in yii2 project using components in order download file path saved in database.

i have setup download button in action column

['class' => 'yii\grid\actioncolumn',                 'template'=>'{update}{pdf}{delete}',                 'buttons'=>[                     // display pdf icon.                    'pdf' => function ($url, $model) {                                     $id = [];                                 foreach ($model->sdsrefs $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;'                 ]   ], 

i have setup link controller action in above code.

my controller action

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,         ]);      } 

in controller action calling component in order download. happens here instead of downloading when click pdf button echoes out content in page. when press pdf button want perform dowload of file.

my download function in component.

 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;     } 

how can achieve result .i.e download when click on pdf action button?

thank you

why don't use sendfile() method of response object?

return yii::$app->response->sendfile($pathfile, $filename); 

check documentation at: http://www.yiiframework.com/doc-2.0/yii-web-response.html#sendfile()-detail


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -