我正在使用 Yii 框架,并且我有网站允许管理员上传文本文件或 pdf。现在我想允许用户单击链接并开始下载该文件。这在 Yii 框架内是如何实现的?
我将文件存储在 Yiiapplication/uploads/downloads/test.txt 中。
我已经尝试了在网上找到的以下代码,但它不起作用。
Yii::app()->request->sendFile(Yii::getPathOfAlias('webroot').'/uploads/downloads/23602414.txt','click me');
我是否需要改进它,它下载的只是一个带有 ' 的文本文件<a href=
' 这不是文件的原始内容。
如果您不想使用扩展,为什么不尝试创建一个简单的方法来强制下载。
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);
}
并创建链接来下载这些文件
<?php echo CHtml::link('Download file',array('youController/download')); ?>
您可以通过在决定标头类型之前检查文件类型来使内容类型更加灵活来改进此代码。可以是 pdf|txt|jpeg|等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)