今天在網上看了下有關圖片上傳的教程,歷經挫折才調試好,如今把相關代碼及其說明貼出來,以供初次使用的朋友們參考。php
yii2.0-ueditor下載路徑:html
https://link.jianshu.com?t=https://github.com/org-yii-china/yii2-ueditor/archive/master.zip
1.下載yii2-ueditor
2.將下載的yii2-ueditor-master 修改 ueditor (注意:修改爲其餘文件名請修改插件內對應的命名空間)
3.將文件方在 根目錄/common/widgets 下便可git
在backend/controllers中新建一個控制器Demo加入如下代碼github
public function actions(){ return [ 'ueditor'=>[ 'class' => 'common\widgets\ueditor\UeditorAction', 'config'=>[ //上傳圖片配置 'imageUrlPrefix' => "", /* 圖片訪問路徑前綴 */ 'imagePathFormat' => "/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */ ] ] ]; }
在對應的渲染頁面,即views下的頁面中web
<?=common\widgets\ueditor\Ueditor::widget(['options'=>['initialFrameWidth' => 850,]])?>
options 填寫配置編輯器的參數(參考ueditor官網)json
<?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'content')->widget('common\widgets\ueditor\Ueditor',[ 'options'=>[ 'initialFrameWidth' => 850, ] ]) ?> ... <?php ActiveForm::end(); ?>
yii2框架整合了百度編輯器,由於文件上傳採用的是yii2自帶的UploadedFile,這就不免umeditor上傳不成功問題,解決問題的只須要兩個操做步驟,咱們來看看具體實現yii2
<?PHP namespace common\models; use yii\base\Model; use yii\web\UploadedFile; /** * UploadForm is the model behind the upload form. */ class Upload extends Model { /** * @var UploadedFile file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file'], ]; } }
use yii\web\UploadedFile; use common\models\Upload; /** * 富文本框的圖片上傳 * @return array */ public function actionUploadImage() { $model = new Upload(); if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, "file"); $dir = '/uploads/ueditor/';//文件保存目錄 if (!is_dir($dir)) mkdir($dir); if ($model->validate()) { $fileName = $model->file->baseName . "." . $model->file->extension; $dir = $dir."/". $fileName; $model->file->saveAs($dir); $info = [ "originalName" => $model->file->baseName, "name" => $model->file->baseName, "url" => $dir, "size" => $model->file->size, "type" => $model->file->type, "state" => "SUCCESS", ]; exit(json_encode($info)); } } }
特別提醒:上述返回的$info信息中state狀態只能是SUCCESS,區分大小寫app
<?php use yii\widgets\ActiveForm; ?> <?= $form->field($model, 'content')->widget('common\widgets\ueditor\Ueditor',[ 'options'=>[ 'initialFrameWidth' => 1050,//寬度 'initialFrameHeight' => 550,//高度 ] ]) ?> <div class="form-group"> <?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end() ?>
其中content是字段名稱框架
關於圖片上傳的能夠看下:yii
https://www.yiichina.com/tutorial/862
在YII2框架中使用UEditor編輯器發佈文章的地址:
https://www.cnblogs.com/felixji/p/6698436.html