为了减少主服务器的负担,把图片部署到七牛云存储。
你得先有个七牛账户,得到accessKey 和 secretKey,然后在里面创建新的存储资源,你会得到一个domain和一个bucket, 需要在yii中进行配置。
第一步
修改Composer配置,修改composer.json
"qiniu/php-sdk": "^7.0",
"crazyfd/yii2-qiniu": "dev-master",
然后update以更新模块
第二步
更新component设置:
'qiniu'=> [
'class' => 'crazyfd\qiniu\Qiniu',
'accessKey' => 'your accessKey',
'secretKey' => 'your secretKey',
'domain' => 'your domain',
'bucket' => 'your bucket',
],
注意crazyfd的七牛SDK里面需要进行一些修改,否则无法从component里获得设置数据:
原始代码为:
protected $accessKey;
protected $secretKey;
protected $bucket;
protected $domain;
function __construct($accessKey, $secretKey, $domain, $bucket = '')
{
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
$this->domain = $domain;
$this->bucket = $bucket;
}
protected的属性无法访问,所以需要把属性改为public, 同时屏蔽到构造函数,修改后的代码为:
public $accessKey;
public $secretKey;
public $bucket;
public $domain;
// function __construct($accessKey, $secretKey, $domain, $bucket = '')
// {
// $this->accessKey = $accessKey;
// $this->secretKey = $secretKey;
// $this->domain = $domain;
// $this->bucket = $bucket;
// }
第三步
在View里面使用
<?=$form->field($model, 'img')>widget(FileInput::className(),[
'options' => ['accept' => 'image/*'],
]) ?>
在Controller里面 在$model->load($post)
之前
$qiniu = Yii::$app->qiniu;
$key = time();
$qiniu->uploadFile($_FILES['your_model_name']['tmp_name']['img'],$key);
$url = $qiniu->getLink($key);
$post[$model->formName()]['img']=$url;
在save()后就可以在数据库中看到存储到七牛端的图片的url了。
如果在七牛的”控件设置”->”访问控制”中选择了公共控件,就可以直接copy图片的url在浏览器中检查是否上传成功
DONE