爲了減少主服務器的負擔,把圖片部署到七牛雲存儲。
你得先有個七牛賬戶,得到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