Uploading a file from Yii

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

I store files in Yiiapplication / uploads / downloads / test.txt.

I have tried the following code I found on the internet, but it doesn't work.

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

      

I need to improve it all it loads is a text file with 'which is not the original content of the file. <a href=

+3


source to share


2 answers


if you'd rather not use an extension, why not try to create a simple force loading method.

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 a link to download these files



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

      

you can improve this code by making the content type more flexible in the type of file to check before choosing the header type. Maybe pdf | txt | jpeg | etc.

+4


source


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

      

0


source







All Articles