File download with Yii

2019-06-28 05:46发布

问题:

I am using the Yii framework and i have the website to allow the admin to upload a text file or a pdf.Now I want to allow the user to click on a link and start downloading that file.How is this achieved inside the Yii framework?

I am storing the files at Yiiapplication/uploads/downloads/test.txt.

I have tried the following code that i have found online but it is not working.

Yii::app()->request->sendFile(Yii::getPathOfAlias('webroot').'/uploads/downloads/23602414.txt','click me');

Do i need to improve on it all it is downloading is a text file with '<a href=' which is not the original content of the file.

回答1:

if you prefer not using extension , why not try to create a simple method to force download.

public function downloadFile($fullpath){
  if(!empty($fullpath)){ 
      header("Content-type:application/pdf"); //for pdf file
      //header('Content-Type:text/plain; charset=ISO-8859-15');
      //if you want to read text file using text/plain header 
      header('Content-Disposition: attachment; filename="'.basename($fullpath).'"'); 
      header('Content-Length: ' . filesize($fullpath));
      readfile($fullpath);
      Yii::app()->end();
  }
}

public function actionDownload(){
  $path = Yii::getPathOfAlias('webroot')."/uploads/downloads/23602414.pdf";
  $this->downloadFile($path);
}

and make link to download those file

<?php echo CHtml::link('Download file',array('youController/download')); ?>

you can improve this code by making content type more flexible by checked file type before decide header type.could be pdf|txt|jpeg|etc.



回答2:

Download Extension from here http://www.yiiframework.com/extension/cfile/

// Set Your file path 
$myfile = Yii::app()->file->set(Yii::app()->basePath.'/../uploads/documents/'.$_GET['file'], true);


 if (Yii::app()->file->set(Yii::app()->basePath.'/../uploads/documents/'.$_GET['file'])->exists){

            $myfile->download();

 } else {

            echo Translate::__('File Not Found');
  }


标签: php yii download