前端代码(编辑器页面):
<style>
#editor—wrapper {
border: 1px solid #ccc;
z-index: 100;
/* 按需定义 */
}
#toolbar-container {
border-bottom: 1px solid #ccc;
}
#editor-container {
height: 500px;
}
</style>
<div class="content">
<div class="content_title">发布文章</div>
<div class="content_form">
<div class="content_form_a"><input placeholder="标题" class="input2" /></div>
<div class="content_form_b">
<!-- wangeditor编辑器 -->
<div id="editor—wrapper">
<div id="toolbar-container"><!-- 工具栏 --></div>
<div id="editor-container"><!-- 编辑器 --></div>
</div>
<div class="content_form_c"><button class="button1">发布</button></div>
</div>
</div>
</div>
<script>
/*1.编辑器声明*/
var html_content;
var { createEditor, createToolbar } = window.wangEditor;
var editorConfig = {
placeholder: 'Type here...',
onChange(editor) {
html_content = editor.getHtml()
console.log('editor content', html_content)
// 也可以同步到 <textarea>
},
MENU_CONF:{}//这里很重要,需要给editorConfig添加MENU_CONF标识
}
/*2.上传图片*/
editorConfig.MENU_CONF['uploadImage'] = {
//服务器页面地址
server: 'upload_img',
//文件名 ,默认值 'wangeditor-uploaded-image'
fieldName: 'custom-field-name',
// 单个文件的最大体积限制,默认为 2M
maxFileSize: 1 * 1024 * 1024, // 1M
// 最多可上传几个文件,默认为 100
maxNumberOfFiles: 10,
// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
allowedFileTypes: ['image/*'],
// 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
meta: {
token: 'xxx',
otherKey: 'yyy'
},
// 将 meta 拼接到 url 参数中,默认 false
metaWithUrl: false,
// 自定义增加 http header
headers: {
Accept: 'text/x-json',
otherKey: 'xxx'
},
// 跨域是否传递 cookie ,默认为 false
withCredentials: true,
// 超时时间,默认为 10 秒
timeout: 5 * 1000, // 5 秒
//上传图片之前
onBeforeUpload(file) {
//console.log(file);
return 1;
},
// 单个文件上传失败
onFailed(file, res) {
console.log(`${file.name} 上传失败`);
console.log(res)
},
// 单个文件上传成功之后
onSuccess(file, res) {
console.log(`${file.name} 上传成功`, res)
}
}
/*3.编辑器实例化*/
var editor = createEditor({
selector: '#editor-container',
html: '<p><br></p>',
config: editorConfig,
mode: 'default', // or 'simple'
})
var toolbarConfig = {}
var toolbar = createToolbar({
editor,
selector: '#toolbar-container',
config: toolbarConfig,
mode: 'default', // or 'simple'
})
</script>
后端代码(上传图片页面):
/**3:上传图片* **/
public function upload_img(){
$file_tmp=$_FILES['custom-field-name']['tmp_name'];
$file_name=$_FILES['custom-field-name']['name'];
$date= date("YmdHis");
//获取文件扩展名
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
//设置随机数
$rand=rand(1000,9999);
$dir = 'upload2/'.$date.$rand.'.'.$ext;
$dir2 = '/upload2/'.$date.$rand.'.'.$ext;
//echo '{"errno":1,"message":'.$file.'}';
move_uploaded_file($file_tmp,$dir);
$success =
[
"errno"=> 0,
"data"=>[
"url"=>$dir2,
"alt"=>"yyy",
"href"=>"zzz"
]
];
$str = json_encode($success);
echo $str;
}
注意:
- 需要在public目录下新建“upload2”文件夹
- 需要在前端代码的“editorConfig”配置中添加“MENU_CONF:{}”项目
- 上传图片和提交表单的操作为两个后端接口操作