準備工做:php
1)http://developer.qiniu.com/article/kodo/kodo-first/quickstart.html 跟着文檔建立七牛賬號,進入我的中心申請認證(須要3天審覈,通常1天就能夠了)和建立存儲空間(上傳的圖片都會在這個空間的內容管理顯示)html
2)http://developer.qiniu.com/code/v7/sdk/php.html 根據裏面的過程跟着執行,用composer安裝數據庫
3)安裝好之後,用以下代碼上傳圖片:bootstrap
控制器: session
use app\models\Ceshi; use yii; //導入七牛相關類 use Qiniu\Auth; use Qiniu\Storage\BucketManager; use Qiniu\Storage\UploadManager; class TestController extends Controller { public function actionIndex() { $model = new Ceshi(); $data = $model->find()->orderBy('id desc')->asArray()->all(); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); //p($post); $image = $this->upload(); if (!$image) { $model->addError('cover', '封面不能爲空'); } else { $post['Ceshi']['image'] = $image; } //p($post); if ($image) { $model->name = $post['Ceshi']['name']; $model->image = $post['Ceshi']['image']; if($model->save()){ p('添加成功'); } p('添加成功11'); Yii::$app->session->setFlash('info', '添加成功'); } else { p('添加失敗'); Yii::$app->session->setFlash('info', '添加失敗'); } } //debug ( 'aaa' ); return $this->render ( 'index',['model'=>$model,'data'=>$data]); } private function upload() { if ($_FILES['Ceshi']['error']['image'] > 0) { return false; } $token=$this->getToken(); $uploadManager=new UploadManager(); $key = uniqid(); //$name=$_FILES['Ceshi']['name']['image']; $filePath=$_FILES['Ceshi']['tmp_name']['image']; $type=$_FILES['Ceshi']['type']['image']; list($ret,$err)=$uploadManager->putFile($token,$key,$filePath,null,$type,false); if($err){//上傳失敗 returnJson("0001",[],"false",$err); }else{//成功 //添加信息到數據庫 return $ret['key']; } } /** * 生成上傳憑證 * @return string */ private function getToken(){ $accessKey = Yii::$app->params['qiniu']['ak']; $secretKey = Yii::$app->params['qiniu']['sk']; $auth=new Auth($accessKey, $secretKey); $bucket = Yii::$app->params['qiniu']['bucket'];//上傳空間名稱 //設置put policy的其餘參數 //$opts=['callbackUrl'=>'http://www.callback.com/','callbackBody'=>'name=$(fname)&hash=$(etag)','returnUrl'=>"http://www.baidu.com"]; return $auth->uploadToken($bucket);//生成token } }
視圖:app
<?php use yii\bootstrap\ActiveForm; use yii\helpers\Html; ?> <?php $form = ActiveForm::begin([ 'options' => [ 'enctype' => 'multipart/form-data', ], //'action' => ['test/ceshi'], ]); ?> <?=$form->field($model, 'name')->textInput()->label('名稱');?> <?=$form->field($model, 'image')->fileInput()->label('圖片');?> <?php echo Html::submitButton('提交', ['class' => 'btn-glow primary']); ?> <?php ActiveForm::end(); ?> <br/> <ul> <?php foreach($data as $v){ ?> <li><?=$v['id']?></li> <li><?=$v['name']?></li> <li><?=$v['image']?></li> <?php } ?> </ul>