如何在项目中 使用七牛云
日期:2017.12.19
作者:zheng wei Yang
一、在项目中添加七牛云 插件
https://packagist.org/packages/crazyfd/yii2-qiniu
二、使用 MVC 方式来展示与说明
C(controller)层:
1:先引入 七牛
use crazyfd\qiniu\Qiniu; //七牛云图床
2:在控制器当中,添加如下方法。
/** * 多文件上传到七牛云图床 * @return [type] [description] */ public function actionAdd(){ $model=new ArticleForm(); if (Yii::$app->request->isPost) { $post=Yii::$app->request->post(); $pics=$this->upload(); // print_r($_FILES); // echo'<hr>'; // print_r($pics); }else{ return $this->render('add',['model'=>$model]); } } // 七牛云 上传图片 private function upload() { if ($_FILES['ArticleForm']['error']['cover'] > 0) { return false; } $qiniu = new Qiniu(ArticleForm::AK, ArticleForm::SK, ArticleForm::DOMAIN, ArticleForm::BUCKET); $key = uniqid(); $qiniu->uploadFile($_FILES['ArticleForm']['tmp_name']['cover'], $key); $cover = $qiniu->getLink($key); $pics = []; foreach ($_FILES['ArticleForm']['tmp_name']['label_img'] as $k => $file) { if ($_FILES['ArticleForm']['error']['label_img'][$k] > 0) { continue; } $key = uniqid(); $qiniu->uploadFile($file, $key); $pics[$key] = $qiniu->getLink($key); } return ['cover' => $cover, 'label_img' => json_encode($pics)]; }
V(view)视图层:
1:视图层就简单多了
<?php use yii\bootstrap\ActiveForm; use yii\helpers\Html; $this->title='创建'; $this->params['breadcrumbs'][]=['label'=>'文章','url'=>['post/index']]; $this->params['breadcrumbs'][]=$this->title; ?> <h2>hello world</h2> <?php $form=ActiveForm::begin() ?> <?= $form->field($model, 'cover')->fileInput(['class' => 'span9'])?> <?= $form->field($model, 'title')->textInput(['autofocus' => true]) ?> <?= $form->field($model, 'label_img[]')->fileInput(['id'=>'product-pics','multiple' => true]) ?> <input type='button' id="addpic" value='增加一个'> <br> <button> 提交 </button> <?php ActiveForm::end(); ?> <?php $js = <<<JS $("#addpic").click(function(){ var pic = $("#product-pics").clone(); $("#product-pics").parent().append(pic); }); JS; $this->registerJs($js); ?>
M(model) 数据处理层:
0:首先得在 七牛云 有账号才行(没有自己申请去)
1:设置 七牛云 的参数,如下图:
// 七牛云 设置参数 const AK = 'a4R8HJ_PCIxVRnhxJnrlX5wVuwXMpVF-4c2chN3y'; const SK = 'BpieYMZReJzolQncfP1uDHVe_DjU2qyNkH4ZE20H'; const DOMAIN = 'onk1t0e35.bkt.clouddn.com'; const BUCKET = 'iblog';