如何下载已在yii框架中保存图像

时间:2015-10-26 10:40:20

标签: yii

我正在使用

$this->widget(
    'CMultiFileUpload',
    array(
        'model' => $model,
        'attribute' => 'Image',
        'accept' => 'jpg|gif|png|doc|docx|pdf',
        'denied' => 'Only doc,docx,pdf and txt are allowed', 
        'max' => 4,
        'remove' => '[x]',
        'duplicate'=>'Already Selected',
    )
);

上传多张图片,我将所有图片保存到数据库中。但我想下载保存的图片。

public function uploadMultifile ($model, $attr, $path)
{
    /*
     * path when uploads folder is on site root.
     * $path='/uploads/doc/'
     */
     if ($sfile = CUploadedFile::getInstances($model, $attr)) {
         foreach ($sfile as $i => $file) {  
             $fileName = "{$sfile[$i]}";
             $formatName=time() . $i . '_' . $fileName;
             $file->saveAs(Yii::app()->basePath . '/' . $formatName);
             $ffile[$i] = $formatName;
         }

         return ($ffile);
     }
}

我想提供图片链接并自动下载。

echo CHtml::link($data->image); 

任何帮助表示感谢。

我试过

 public function actionDownloadImage()
 {
    $model = $this->loadModel($_GET['id']); 
    $fileDir = Yii::app()->basePath.'/Img/';

    Yii::app()
        ->request
        ->sendFile(
            $model->image,
            file_get_contents($fileDir.$model->image),
            $model->image
        );
 }    

但是给出错误..

1 个答案:

答案 0 :(得分:0)

您尚未定义文件夹路径以在uploadMultifile()操作中保存图片。因此,您无法从" Img"中获得所需的图像。命名文件夹。您必须在uploadMultifile()操作中进行以下更改:

public function uploadMultifile ($model, $attr, $path)
{
    /*
     * path when uploads folder is on site root.
     * $path='/uploads/doc/'
     */
     if ($sfile = CUploadedFile::getInstances($model, $attr)) {
         foreach ($sfile as $i => $file) {  
             $fileName = "{$sfile[$i]}";
             $formatName=time() . $i . '_' . $fileName;
             $file->saveAs(Yii::app()->basePath . '/Img/' . $formatName); // specify folder path where you have to save image
             $ffile[$i] = $formatName;
         }

         return ($ffile);
     }
}

希望这会有所帮助。