我正在使用Yii框架,并且我拥有允许管理员上传文本文件或pdf的网站。现在我想允许用户单击链接并开始下载该文件。如何在Yii框架内实现?
我将文件存储在Yiiapplication / uploads / downloads / test.txt。
我尝试了以下在网上找到的代码,但无法正常工作。
Yii::app()->request->sendFile(Yii::getPathOfAlias('webroot').'/uploads/downloads/23602414.txt','click me');
Run Code Online (Sandbox Code Playgroud)
我是否需要改进所有下载<a href=的内容,即带有' ' 的文本文件,这不是文件的原始内容。
小智 5
如果您不喜欢使用extension,为什么不尝试创建一个简单的方法来强制下载。
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);
}
Run Code Online (Sandbox Code Playgroud)
并链接下载这些文件
<?php echo CHtml::link('Download file',array('youController/download')); ?>
Run Code Online (Sandbox Code Playgroud)
您可以通过在确定标头类型之前通过检查文件类型使内容类型更灵活来改进此代码。可以为pdf | txt | jpeg | etc。
从这里下载扩展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');
}
Run Code Online (Sandbox Code Playgroud)