yii画像アップロードチュートリアル

7861 ワード

今日はネットで画像のアップロードに関するチュートリアルを見て、挫折してやっとデバッグして、今関連コードとその説明を貼って、初めて使う友达の参考にします.
Model
<?php

class Upload extends CActiveRecord {

    public $image;

    public static function model($className = __CLASS__) {
        return $className;
    }

    public function tableName() {
        return '{{resource}}';
    }

    public function rules() {

        return array(
            array('image', 'file', 'types'=>'jpg, gif, png')
        );
    }

}

注意:resourceはデータテーブルで、テーブルの接頭辞はmainで使用できます.php内の設定は、友達がファイルのアップロードを見たときにmainに慣れていると信じています.php位置がどこにあるか、動作メカニズム.
Controller
<?php

class UploadController extends Controller {

    public function actionIndex() {
        $model=new Upload;
        if(isset($_POST['Upload'])) {
            $model->image=CUploadedFile::getInstance($model,'image');
            $ext = $model->image->getExtensionName();
            $fileName = uniqid() . '.' . $ext;
            $model->image->saveAs('assets/' . $fileName);

        }
        $this->renderPartial('index', array('model'=>$model));
    }

}

注:saveAsの中はピクチャーを保存してアップロードした後の住所で、コードを追跡して発見することができて、このパラメータはmove_ですuploaded_file関数の2番目のパラメータは、必ずファイル名でなければなりません.
View
<meta charset="utf-8">
<?php echo CHtml::form(SITE_URL . 'admin/upload/index','post',array('enctype'=>'multipart/form-data')); ?>
<?php echo CHtml::activeFileField($model, 'image'); ?>
<?php echo CHtml::submitButton('  ');?>
<?php echo CHtml::endForm(); ?>

メモ:上のSITE_URLはプロジェクト定義の定数、つまりプロジェクトのURLです
上記の手順を経て、友达は成功した画像をアップロードすることができ、プロジェクトの下のassetsディレクトリの下でアップロードした画像を見つけることができると信じています.yiiにサムネイルの方法がないことを発見したのでthinkphpサムネイルの方法を統合し、以下のコードをImageとして保存した.phpはプロジェクトの下にあるprotected/extensionsディレクトリの下に置く
<?php

class Image extends CController {

    /**
      +----------------------------------------------------------
     *       
     *
      +----------------------------------------------------------
     * @static
     * @access public
      +----------------------------------------------------------
     * @param string $image      
      +----------------------------------------------------------
     * @return mixed
      +----------------------------------------------------------
     */

    static function getImageInfo($img) {
        $imageInfo = getimagesize($img);
        if ($imageInfo !== false) {
            $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
            $imageSize = filesize($img);
            $info = array(
                "width" => $imageInfo[0],
                "height" => $imageInfo[1],
                "type" => $imageType,
                "size" => $imageSize,
                "mime" => $imageInfo['mime']
            );
            return $info;
        } else {
            return false;
        }
    }

    /**
      +----------------------------------------------------------
     *      
      +----------------------------------------------------------
     * @static
     * @access public
      +----------------------------------------------------------
     * @param string $image    
     * @param string $type     
     * @param string $thumbname       
     * @param string $maxWidth    
     * @param string $maxHeight    
     * @param string $position        
     * @param boolean $interlace       
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     */
    static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
        //       
        $info = Image::getImageInfo($image);
        if ($info !== false) {
            $srcWidth = $info['width'];
            $srcHeight = $info['height'];
            $type = empty($type) ? $info['type'] : $type;
            $type = strtolower($type);
            $interlace = $interlace ? 1 : 0;
            unset($info);
            $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); //       
            if ($scale >= 1) {
                //           
                $width = $srcWidth;
                $height = $srcHeight;
            } else {
                //      
                $width = (int) ($srcWidth * $scale);
                $height = (int) ($srcHeight * $scale);
            }

            //     
            $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
            if(!function_exists($createFun)) {
                return false;
            }
            $srcImg = $createFun($image);

            //     
            if ($type != 'gif' && function_exists('imagecreatetruecolor'))
                $thumbImg = imagecreatetruecolor($width, $height);
            else
                $thumbImg = imagecreate($width, $height);
              //png gif      by luofei614
            if('png'==$type){
                imagealphablending($thumbImg, false);//         (           )
                imagesavealpha($thumbImg,true);//        alpha     (           )    
            }elseif('gif'==$type){
                $trnprt_indx = imagecolortransparent($srcImg);
                 if ($trnprt_indx >= 0) {
                        //its transparent
                       $trnprt_color = imagecolorsforindex($srcImg , $trnprt_indx);
                       $trnprt_indx = imagecolorallocate($thumbImg, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                       imagefill($thumbImg, 0, 0, $trnprt_indx);
                       imagecolortransparent($thumbImg, $trnprt_indx);
              }
            }
            //     
            if (function_exists("ImageCopyResampled"))
                imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
            else
                imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);

            //  jpeg        
            if ('jpg' == $type || 'jpeg' == $type)
                imageinterlace($thumbImg, $interlace);

            //     
            $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
            $imageFun($thumbImg, $thumbname);
            imagedestroy($thumbImg);
            imagedestroy($srcImg);
            return $thumbname;
        }
        return false;
    }

}
?>

プロジェクトの下のprotected/config/main.phpにimportフィールドを追加
// autoloading model and component classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
        'application.extensions.*',   #    ,       
    ),

さらに上のControllerに
public function actionIndex() {
        $model=new Upload;
        if(isset($_POST['Upload'])) {
            $model->image=CUploadedFile::getInstance($model,'image');
            $ext = $model->image->getExtensionName();
            $fileName = uniqid() . '.' . $ext;
            $model->image->saveAs('assets/' . $fileName);

            //      
            Image::thumb('assets/' . $fileName, 'assets/' . uniqid() . '.' . $ext);
        }
        $this->renderPartial('index', array('model'=>$model));
    }

今回は完璧です.