title: Yii2 file download using custom components
body: <p>In yii2 project I am using components in order to download a file whose path is saved in my database. </p>
  
  <p>I have setup the download button in my action column</p>
  
  <pre><code>['class' =&gt; 'yii\grid\ActionColumn',
                  'template'=&gt;'{update}{pdf}{delete}',
                  'buttons'=&gt;[
                      // to display pdf icon.
                     'pdf' =&gt; function ($url, $model) {    
                                  $id = [];
                                  foreach ($model-&gt;sdsrefs as $mod)
                                      $id[] = $mod-&gt;file_id;
                                      return Html::a('&lt;span class="glyphicon glyphicon-download-alt"&gt;&lt;/span&gt;', Url::to(['product/download', 'id' =&gt; implode($id)]), [
  
                                     ]);                      
                              }
                  ],
                  'options'=&gt;[
                      'style'=&gt;'width:70px;'
                  ]
    ],
  </code></pre>
  
  <p>I have setup the link to the controller action in the above code.</p>
  
  <p>My controller action</p>
  
  <pre><code>public function actionDownload($id)
      {
          Yii::$app-&gt;files-&gt;downloadFile($id);
          $searchModel = new ProductSearch();
          $dataProvider = $searchModel-&gt;search(Yii::$app-&gt;request-&gt;queryParams);
  
  
          return $this-&gt;render('index', [
              'searchModel' =&gt; $searchModel,
              'dataProvider' =&gt; $dataProvider,
          ]);
  
      }
  </code></pre>
  
  <p>In the controller action I am calling the component in order to download. What happens here is instead of downloading when i click the PDF button it echoes out the content in the page. When I press the Pdf button I want it perform dowload of the file.</p>
  
  <p>my download function in the component.</p>
  
  <pre><code> 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-&gt;file_name);
              header('Content-Length: ' . filesize($filepath));
              readfile("$filepath");
          }else{
              echo "file not exist: ".$filepath;            
          }
          exit;
      }
  </code></pre>
  
  <p>How can I achieve my result .i.e download when I click on the pdf action button?</p>
  
  <p>Thank you</p>