简体   繁体   中英

File download with Yii

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM