下载上传到yii本地文件夹的文件


Downloading files which were uploaded to local folder in yii

我在 Yii 中创建了一个上传文件页面,它成功地保存在数据库和本地文件夹中,我一直在研究如何下载这个文件,我遇到了这个并试图遵循它。

在我的模型中,我将其添加到规则中:

array('location', 'file', 'types'=>'jpg,jpeg, png, doc,docx,xls,xlsx,pdf',
                  'maxSize'=>1024 * 1024 * 3, // 3MB
                  'tooLarge'=>'The file was larger than 3MB. Please upload a smaller file.',
                   'allowEmpty' => true),    
        );

我的控制器如下所示:

public function actionDisplaySavedImage()
{
    $model=$this->loadModel($_GET['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-Disposition: attachment; filename='.$model->location);
        echo $model->location;
}

我的观点是:

<?php echo CHtml::link('Download Here',array('displaySavedImage','id'=>$model->primaryKey)); ?>

我可以下载文件,但是当我打开它时,它是一个混乱的文件类型。

例如,如果我下载图像,则会出现Windows照片查看器,但它会显示一条文本,指出"不支持文件类型"或类似内容。

如果我尝试使用不同的文件类型(如.docx),也是如此。Microsoft词会说它不受支持。

请帮忙

public function actionDisplaySavedImage($id){
    $model = $this->loadModel($id);
    $upload_path = Yii::app()->params['uploadPath'] . $model->location; // /var/home/site/upload/image.jpg
    if (file_exists($upload_path)) {
        Yii::app()->getRequest()->sendFile($model->location, file_get_contents($upload_path));
    } else {
        $this->render('httperror404');
    }
}

以下是我用于从本地文件夹下载csv文件的代码。 试试这个 希望它也适合你。您可以根据需要更改标题。

$reportFileName = pathinfo($model->report_file);
$csvFileName = "your file name";
header('Content-Type: application/csv');
header('Content-Length: '.filesize($folder.$csvFileName.'.csv'));
header('Content-disposition: inline; filename='.$csvFileName.'.csv');
echo file_get_contents($folder.$csvFileName.'.csv');