teamoping 2016-08-04 15:38:51 6212次浏览 0条评论 6 2 0

1、自定义图片上传类 backend/components/Upload.php

<?php
namespace agent\components;

use yii;
use yii\base\Object;
use yii\web\UploadedFile;

class Upload extends Object
{
    /**
     * [UploadPhoto description]
     * @param [type]  $model      [实例化模型]
     * @param [type]  $path       [图片存储路径]
     * @param [type]  $originName [图片源名称]
     * @param boolean $isthumb    [是否要缩略图]
     */
    public function UploadPhoto($model,$path,$originName,$isthumb=false){
        $root = $_SERVER['DOCUMENT_ROOT'].'/'.$path;
        //返回一个实例化对象
        $files = UploadedFile::getInstance($model,$originName);
        $folder = date('Ymd')."/";
        $pre = rand(999,9999).time();
        if($files && ($files->type == "image/jpeg" || $files->type == "image/pjpeg" || $files->type == "image/png" || $files->type == "image/x-png" || $files->type == "image/gif"))
        {
            $newName = $pre.'.'.$files->getExtension();
        }else{
            die($files->type);
        }
        if($files->size > 2000000){
            die("上传的文件太大");
        }        
        if(!is_dir($root.$folder))
        {
            if(!mkdir($root.$folder, 0777, true)){
                die('创建目录失败...');
            }else{
            //    chmod($root.$folder,0777);
            }
        }
        //echo $root.$folder.$newName;exit;
        if($files->saveAs($root.$folder.$newName))
        {
            if($isthumb){
                $this->thumbphoto($files,$path.$folder.$newName,$path.$folder.'thumb'.$newName);
                return $path.$folder.$newName.'#'.$path.$folder.'thumb'.$newName;
            }else{
                return $path.$folder.$newName;
            }
            
        }
    }
}
?>

2、注册组件 backend/config/main.php

'components' => [
    //自定义图片上传类
    'imgload' => [
        'class' => 'agent\components\Upload'
    ],
]

3、控制器部分

<?php
use backend\components\Upload;

public function actionArtadd(){
    $model = new Aarticle();
    if ($model->load(Yii::$app->request->post())) {
        //cover为表中的字段名
        $img = Yii::$app->imgload->UploadPhoto($model,'uploads/article/','cover');
        $model->cover = $img;//存入表中
        if($model->save()){
            Yii::$app->getSession()->setFlash('info', '添加成功!');
            return $this->redirect(['xxx']);
        }else{
            Yii::$app->getSession()->setFlash('info', '添加失败!');
            @unlink($img);
            return $this->redirect(['xxx']);
        }
    }
    //代码略
}
?>

4、视图 (部分代码)

<?= $form->field($model, 'cover', [
    'options'=>['class'=>''],
    'inputOptions' => ['class' => 'form-control'],
])->fileInput()->label(false); ?>
觉得很赞
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册