Display images from protected folder

风格不统一 提交于 2020-01-03 00:02:08

问题


I have a protected folder within Yii and I'm looking to display some of those images within the site. I've tried the following code and it works within the site/index controller in that it returns just the image I wanted.

However when I tried to separate the code it didn't work. Any help is appreciated.

Model

    public function getImage() // will take file identifier as @param       
{

    $imageID = '2562584569'; // will eventually be dynamically assigned

    $image = Images::model()->find('tmp_name=:id', array('id' => $imageID)); 

    $dest = Yii::getPathOfAlias('application.uploads');

    $file = $dest .'/' . $image->tmp_name . '.' . $image->extension;

    if(file_exists($file)){
    ob_clean();
    header('Content-Type:' . $image->logo_type);
    readfile($file);
    exit;
    }

}

And in the view

CHtml::link('<img src="' . Yii::app()->request->baseUrl .'/images/image" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));

Thanks

Jonnny


回答1:


"protected" folder are not accessible from the client browser. This prevents people to have access to important files, like your source code.

If you want to store images inside "protected" and want them to be accessible, you need to publish them using CAssetManager.

Usage is something like:

$path = Yii::app()->basePath.'/path-inside-protected';
$yourImageUrl = Yii::app()->assetManager->publish($path);

Yii will then use the file as an asset, coping it to the "assets" folder, sibling to "protected". After that, you can just use the url returned on your HTML.

<img src="<?php echo $yourImageUrl ?>">



回答2:


I went about it like this

CHtml::link('<img src="' . $this->createUrl('/images/image', array('data'=>$data['data'])) . '" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));

Model

public function actionImage($data)       
{

$image = Images::model()->find('tmp_name=:data', array('id' => $data)); 

$dest = Yii::getPathOfAlias('application.uploads');

$file = $dest .'/' . $image->tmp_name . '.' . $image->extension;

if(file_exists($file)){
ob_clean();
header('Content-Type:' . $image->logo_type);
readfile($file);
exit;
}

}

Thanks for all help



来源:https://stackoverflow.com/questions/17889381/display-images-from-protected-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!