Yii2使用七牛云存储上传文件

引入Qiniu

借鉴了Github上的yii2-qiniu

在composer.json的require中加入下面的代码并更新。

1
"crazyfd/yii2-qiniu": "dev-master",

在config/params.php中加入一下代码:

1
2
3
4
5
6
7
'qiniu' =>[
# 在七牛官网查询相关参数
'accessKey' => 'your access key',
'secretKey' => 'your secret key',
'domain' => 'your domain',
'bucket' => 'your bucket',
],

直接使用

在DemoController.php中加入

1
2
3
4
5
6
7
8
9
10
11
12
public function qiniuUpload($file)
{

$ak = Yii::$app->params['qiniu']['accessKey'];
$sk = Yii::$app->params['qiniu']['secretKey'];
$domain = Yii::$app->params['qiniu']['domain'];
$bucket = Yii::$app->params['qiniu']['bucket'];
$qiniu = new Qiniu($ak, $sk,$domain, $bucket);
$key = time();
$qiniu->uploadFile($file, $key);
$url = $qiniu->getLink($key);
return $url;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public function actionCreate()
{

$model = new Image();
if ($model->load(Yii::$app->request->post())) {
$file = $_FILES["myfile"]["tmp_name"];
if(file_exists($file)){
$response_url = $this->qiniuUpload($file);
$model->image = $response_url;
}
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}else{
return $this->render('create', [
'model' => $model,
'categories' => $categories,
]);
}
}else{
return $this->render('create', [
'model' => $model,
'categories' => $categories,
]);
}
}

在views/image/form.php中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']
]); ?>

<?= $form->field($model, 'image')->fileInput(['name' => 'myfile']) ?>
<?php if($model->image){ ?>
<div class="preview">
<img src="<?= Html::encode($model->image)?>" width="100px">
</div>
<?php } ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? '新建' : '更新', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!