用Yii下载文件 [英] File download with Yii

查看:48
本文介绍了用Yii下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Yii框架,并且我有一个网站允许管理员上传文本文件或pdf文件。现在我想允许用户单击链接并开始下载该文件。如何在内部实现Yii框架?

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

我将文件存储在Yiiapplication / uploads / downloads / test.txt。

I am storing the files at Yiiapplication/uploads/downloads/test.txt.

我已经尝试了以下在网上找到的代码,但无法正常工作。

I have tried the following code that i have found online but it is not working.

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

我是否需要对其进行所有改进?它正在下载的是带有' < a href = ,而不是文件的原始内容。

Do i need to improve on it all it is downloading is a text file with '<a href=' which is not the original content of the file.

推荐答案

如果您不喜欢使用extension,为什么不尝试创建一个简单的方法来强制下载。

if you prefer not using extension , why not try to create a simple method to force download.

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 link to download those file

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

您可以通过在决定标题类型之前通过检查文件类型使内容类型更加灵活来改进此代码。是pdf | txt | jpeg |等。

you can improve this code by making content type more flexible by checked file type before decide header type.could be pdf|txt|jpeg|etc.

这篇关于用Yii下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆