File download with Yii

天涯浪子 提交于 2019-12-23 12:26:01

问题


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


来源:https://stackoverflow.com/questions/26041329/file-download-with-yii

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!