Я переписал свой код, как показано ниже:
Моя модель:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return array(
array('file', 'file', 'types'=>'pdf'),
);
}
public function downloadFile($fullpath){
$dir = Yii::getPathOfAlias('application.uploads');
$filename= $fullpath;
if(!empty($fullpath)){
$file = $dir."\\"."$filename";
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=$filename");
@readfile($file);
Yii::app()->end();
}
else {return false;}
}
}
Мой контроллер:
<?php
class UploadController extends Controller
{
public $file;
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$this->file=CUploadedFile::getInstance($model,'file');
$file=$this->file;
if($model->validate()){
$uploaded = $file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}
public function actionDownload($id){
$path = Yii::getPathOfAlias('/yiiroot/trackstar/protected/uploads/')."$id";
$upload=new Upload();
$upload->downloadFile($path);
}
}
Мой вид:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array
('enctype'=>'multipart/form-data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, 'file')?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
<br/>
<?php $model=new Upload(); ?>
<?php if(isset($_POST['Upload'])){$model->attributes=$_POST['Upload'];
$this->file=CUploadedFile::getInstance($model,'file');
echo CHtml::link('Download file',array('/upload/download','id'=>$this->file->getName()));
}?>
см .: PHP getName () Функция