Button Download

Hallo everybody,

I am new to yii. I have requirement to upload a file to database & then download it from database. I’m using CUploadedFile for uploading file to server.

i have NaskahController for upload:




public function actionCreate()

	{

		$model=new Naskah;


		if(isset($_POST['Naskah']))

		{

			$model->attributes=$_POST['Naskah'];

			$model->lampiran=CUploadedFile::getInstance($model,'lampiran');

			

			

			if($model->save())

				$this->redirect(array('sent','id'=>$model->id_naskah));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}



Can anyone please let me know how to add a button for DOWNLOAD that file and then this action can be appear (like image).Any help would be greatly appreciated.

Thanks :rolleyes:

You want to save files on server or in DB?

hemc thanks for your response. i want to save files on server

Hi, I advice you to create an action in your controller. In this action you must have your http header like :




public function actionDownloadFile($id,$file_field,$file_name)

  {

    $model=$this->loadModel($id);

    header('Pragma: public');

    header('Expires: 0');

    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    header('Content-Transfer-Encoding: binary');

    //header('Content-length: 1665');

    header('Content-Type: text/html');

    header('Content-Disposition: attachment; filename='.$file_name);

              

    echo stream_get_contents($model->$file_field,-1,0);     

  }



then in your echo, you put your file. For example, my file is in database so I give the model field which contains the binary file. If the file is in on server you can use php simply function to print it.

In parameter I have id, file_field, and file_name, you can adapte it depending on what you want to do exactly.

the way/link to call this action is like :




/your/ii/app/yourModelName/downloadFile?id=my_id&file_field=my_file_field&file_name=my_file_name



The best thing to do is to put this function in a global controller, like "MyController" in order to all controllers can benefit of that.

for more info, check out my post http://www.yiiframework.com/forum/index.php/topic/29774-actiondownload-for-my-download-link/page__gopid__213944#entry213944

$dir_path="Path of your System up to the last Folder";

	$name=File name;


	$path=$dir_path."/$name";


	if(file_exists($dir_path))


	{


	  return Yii::app()->getRequest()->sendFile($name, @file_get_contents($path));


	}