html: <div class="layui-form-item"> <label class="layui-form-label"><strong style="color:red;">*</strong>正文内容</label> <div class="layui-input-block" style="width: 600px"> <?= WangEditorWidget::widget([ 'name' => 'content', 'uploadImageServer' => '/file/upload-img?format=url&dirname=article&filename=img', 'uploadFileName' => 'img', 'customConfig' => [ 'menus' => [ 'head', // 标题 'bold', // 粗体 'fontSize', // 字号 'italic', // 斜体 'foreColor', // 文字颜色 'backColor', // 背景颜色 'link', // 插入链接 'list', // 列表 'justify', // 对齐方式 'quote', // 引用 'image', // 插入图片 //'video', // 插入视频 'undo', // 撤销 'redo' // 重复 ] ], ]) ?> </div> </div>
php:
public function actionUploadImg() { $request = \Yii::$app->request; if($request->isPost){ \Yii::$app->response->format = Response::FORMAT_JSON; //返回数据格式,默认返回url, 支持path参数,返回相对于网站根目录的路径 $format = $request->get('format', 'url'); //提交输入框名称 $fileInputName = $request->get('filename', 'file'); $file = UploadedFile::getInstanceByName($fileInputName); //目录名称 $dirname = $request->get('dirname', ''); //验证模型 $uploadValidateModel = new UploadValidateModel('upload_img'); $uploadValidateModel->file = $file; if(!$uploadValidateModel->validate()){ $errorMsg = $this->getValidateError($uploadValidateModel); return ['errno' => 1, 'msg' => $errorMsg]; } //组合相对路径 if(!empty($dirname)){ $relative_path = trim($dirname, '/').'/'.date('Y').'/'.date('m').'/'.date('d').'/'; }else{ $relative_path = date('Y').'/'.date('m').'/'.date('d').'/'; } //组合绝对路径 $absolute_path = rtrim(\Yii::$app->params['upload_dir'], '/').'/'.$relative_path; if(!file_exists($absolute_path)){ try{ FileHelper::createDirectory($absolute_path, 0777, true); }catch (\Exception $e){ return ['errno'=>1, 'msg' => '目录创建失败,'.$e->getMessage()]; } } //文件名 $filename = date('His').md5($file->getBaseName()).mt_rand(1000, 9999).'.'.$file->getExtension(); //保存文件 $file->saveAs($absolute_path.$filename); $data = ''; switch ($format){ case 'url': $data = rtrim(\Yii::$app->params['cdn_url_prefix'], '/').'/'.$relative_path.$filename; break; case 'path': $data = '/'.$relative_path.$filename; break; } return ['errno'=>0, 'data' => [$data]]; } }