wangeditor: 上传图片+上传视频+上传附件(自定义)完整使用
wangeditor: 上传图片+上传视频+上传附件(自定义)完整使用一:项目需求:①角色为管理员可以新增编辑文章 + ②点击可以看文章详情 +③ 角色为管理员可以修改编辑文章二:效果:①角色为管理员可以新增编辑文章步骤:①下载安装相关依赖 npm i wangeditor --save②引入③初始化创建编辑器代码中的initialEditor函数④自定义上传附件按钮主要思路:在编辑器上增加新的菜
wangeditor: 上传图片+上传视频+上传附件(自定义)完整使用
一:项目需求:①角色为管理员可以新增编辑文章 + ②点击可以看文章详情 +③ 角色为管理员可以修改编辑文章
二:效果:
①角色为管理员可以新增编辑文章
步骤:
①下载安装相关依赖 npm i wangeditor --save
②引入
③初始化创建编辑器
代码中的initialEditor函数
④自定义上传附件按钮
主要思路:在编辑器上增加新的菜单按钮 --》实例化按钮 --》结合ant-vue中的上传文件的组件,点击上传附件的按钮点击上传附件
// 菜单 key ,各个菜单不能重复
const menuKey = 'alertMenuKey'
editor = new E('#editor')
// editor.txt.clear() //清空富文本的内容
editor.menus.extend(menuKey, AlertMenu)
editor.config.menus.push(menuKey)
// 菜单点击事件
clickHandler() {
// 做任何你想做的事情
document.getElementById("tiggerPick").click();
}
要点:①自定义上传图片和视频方法 ②如何判断Dom上编辑器是否被创建
具体代码:
Markup
<template>
<a-modal
title="新增知识库"
:width="900"
:visible="visible"
:confirmLoading="confirmLoading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-spin :spinning="confirmLoading">
<a-form :form="form">
<a-form-item
label="标题"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<a-input placeholder="请输入标题" v-decorator="['title', {rules: [{required: true, message: '请输入标题!'}]}]" />
</a-form-item>
<a-form-item
label="来源"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<a-input placeholder="请输入来源" v-decorator="['source', {rules: [{required: true, message: '请输入来源!'}]}]" />
</a-form-item>
<a-form-item
label="摘要"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<a-textarea
placeholder="请输入摘要"
v-decorator="['summary', {rules: [{required: true, message: '请输入摘要!'}]}]"
:auto-size="{ minRows: 3}"
/>
</a-form-item>
<a-form-item
label="类型"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
style="margin-left:-150px;"
>
<a-select
style="width: 100%"
placeholder="请选择类型"
v-decorator="['type', {rules: [{ required: true, message: '请选择类型' }]}]">
<a-select-option v-for="(item,index) in typeData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item
label="封面"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<!-- <a-input placeholder="请输入封面" v-decorator="['coverimg']" /> -->
<div :key="imgKey">
<a-upload
list-type="picture-card"
:file-list="fileList"
@change="handleChange"
@preview="handlePreview"
:before-upload="beforeImg"
:customRequest="uploadMethod"
>
<div v-if="fileList.length < 1">
<a-icon type="plus" />
<div class="ant-upload-text">
上传封面
</div>
</div>
</a-upload>
</a-upload>
</div>
<a-modal :visible="previewVisible" :footer="null" @cancel="imghandleCancel">
<img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</a-form-item>
<a-form-item
label="内容"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
style="margin-left:-150px;"
>
<div id="editor" style="width:810px;"></div>
<div class="accessory" style="margin-left:-35px;position: relative;">
<span >附件: </span>
<a-upload
:file-list="refileList"
:before-upload="beforeUpload"
:customRequest="fileUpload"
:remove="handleRemove"
>
<a-button v-show="false" style="width: 220px;" id="tiggerPick"> <a-icon type="upload" /> 请选择文件资源 </a-button>
</a-upload>
</div>
</a-form-item>
<!-- <a-form-item
label="附件路径"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
>
<a-input placeholder="请输入附件路径" v-decorator="['filepath']" />
</a-form-item>
<a-form-item
label="排序"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
>
<a-input placeholder="请输入排序" v-decorator="['sort']" />
</a-form-item> -->
</a-form>
</a-spin>
</a-modal>
</template>
<script>
import "@/components/bottomReset.less"
import "@/components/subfile.less"
import { knowledgeBaseAdd } from '@/api/modular/main/knowledgebase/knowledgeBaseManage'
import E from 'wangeditor'
const { BtnMenu } = E
// 自定义上传附件菜单
class AlertMenu extends BtnMenu {
constructor(editor) {
// data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
const $elem = E.$(
`<div class="w-e-menu" data-title="上传附件">
<a-button style="width: 40px;height: 40px;">附件</a-button>
</div>`
)
super($elem, editor)
}
// 菜单点击事件
clickHandler() {
// 做任何你想做的事情
document.getElementById("tiggerPick").click();
}
// 菜单是否被激活(如果不需要,这个函数可以空着)
tryChangeActive() {
// 激活菜单
// 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
// 2. this.this.isActive === true
this.active()
}
}
/*封面上传图片预览 */
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
let editor;
export default {
data () {
return {
labelCol: {
xs: { span: 24 },
sm: { span: 5 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 12 },
},
typeData: [],
visible: false,
confirmLoading: false,
form: this.$form.createForm(this),
/*封面上传参数 */
previewImage:'',//预览图片地址
previewVisible:false,//预览
fileList:[],
coverimg:'',//存放封面图片地址
/*附件上传参数 */
refileList:[],
/*富文本内容 */
content:'',
imgKey: '',
// 附件路径
filepath:'',
}
},
mounted(){
},
watch: {
visible() {
if (this.visible) {
this.imgKey = ''
} else {
this.imgKey = Math.random()
}
}
},
methods: {
// 初始化方法
add (record) {
this.visible = true
const typeOption = this.$options
this.typeData = typeOption.filters['dictData']('knowledge_type')
this.$nextTick(() =>{
if (editor==null){
this.initialEditor()
}else {
editor.destroy();//判断编辑器是否被创建,如果创建了就先销毁。
this.initialEditor()
}
})
},
/*富文本编辑器初始化 */
initialEditor(){
// 菜单 key ,各个菜单不能重复
const menuKey = 'alertMenuKey'
editor = new E('#editor')
// editor.txt.clear() //清空富文本的内容
editor.menus.extend(menuKey, AlertMenu)
editor.config.menus.push(menuKey)
editor.config.height = 300
const that = this;
// 图片
editor.config.customUploadImg = function (resultFiles, insertImgFn) {
// resultFiles 是 input 中选中的文件列表
// insertImgFn 是获取图片 url 后,插入到编辑器的方法
console.log(resultFiles[0],'...');
const formData = new FormData();
formData.append('file', resultFiles[0]);
formData.append('type', 'image');
that.axios.post('/sysFileInfo/upload',formData)
.then(res => {
console.log(res);
if(res.success){
// 上传图片,返回结果,将图片插入到编辑器中
insertImgFn(res.data)
}
}).catch(err =>{
})
}
// 视频
editor.config.customUploadVideo = function (resultFiles, insertVideoFn) {
const formData = new FormData();
formData.append('file', resultFiles[0]);
formData.append('type', 'image');
console.log(formData);
that.axios.post('/sysFileInfo/upload',formData)
.then(res => {
if(res.success){
// 上传视频,返回结果,将图片插入到编辑器中
insertVideoFn(res.data)
}
}).catch(err =>{
})
}
editor.config.excludeMenus = ['link']
// 注意,先配置 height ,再执行 create()
editor.create()
},
/*
封面上传
*/
//控制图片预览显示
imghandleCancel() {
this.previewVisible = false;
},
// 在上传之前做出判断
beforeImg(file){
console.log('tupian',file);
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
this.$message.error('只能上传图片文件,请重新上传');
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
return false
}
},
// 上传
uploadMethod(file){
let image = "image"
const formData = new FormData();
formData.append('file', file.file);
formData.append('type', image);
this.axios.post('/sysFileInfo/upload',formData)
.then(res => {
console.log(res);
if(res.success){
this.coverimg = res.data
file.onSuccess();
}
}).catch(err =>{
file.onError() //上传失败
})
},
// 预览
async handlePreview(file) {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
},
handleChange({ fileList }) {
this.fileList = fileList
},
/*附件上传*/
// 移除
handleRemove(file) {
const index = this.refileList.indexOf(file);
const newFileList = this.refileList.slice();
newFileList.splice(index, 1);
this.refileList = newFileList;
},
// 上传之前的限制
beforeUpload(file){
console.log('file',file);
if(this.refileList.length === 0){
this.refileList = [...this.refileList, file];
}else{
this.$message.error('仅支持上传一个文件');
}
},
//上传
fileUpload(){
const formData = new FormData();
if(this.refileList.length){
this.refileList.forEach(file => {
formData.append('file', file);
formData.append('type', 'image');
});
this.axios.post('/sysFileInfo/upload',formData)
.then(res => {
console.log(res);
if(res.success){
this.filepath = res.data
}
}).catch((err => {
this.$message.error('上传失败');
}))
}
},
/**
* 提交表单
*/
handleSubmit () {
const { form: { validateFields } } = this
this.confirmLoading = true
console.log('富文本内容',editor.txt.html());
this.content = editor.txt.html()
validateFields((errors, values) => {
if (!errors) {
for (const key in values) {
if (typeof (values[key]) === 'object') {
values[key] = JSON.stringify(values[key])
}
}
values.coverimg = this.coverimg
values.content = this.content
values.filepath = this.filepath
knowledgeBaseAdd(values).then((res) => {
if (res.success) {
this.$message.success('新增成功')
this.confirmLoading = false
this.$emit('ok', values)
this.handleCancel()
} else {
this.$message.error('新增失败')// + res.message
}
}).finally((res) => {
this.confirmLoading = false
})
} else {
this.confirmLoading = false
}
})
},
handleCancel () {
this.form.resetFields()
this.visible = false
this.refileList = []
this.fileList = []
}
}
}
</script>
<style lang="less" scoped>
.accessory-text{
position: absolute;
left: 0;
bottom: 0;
}
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.plus{
font-size: 100px;
color: #dfdfdf;
width: 20px;
height: 20px;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
②
具体代码:重点 v-html
Markup
<a-modal
title=""
:width="900"
:footer="null"
:visible="detailVisible"
:confirmLoading="confirmLoading"
@cancel="detailHandleCancel"
style="height: auto;"
>
<div class="content-box">
<h1>{{headline}}</h1>
<div class="content-info">
<span>时间:{{time}}</span>
<span>来源:{{source}}</span>
<span>分类:{{classify}}</span>
</div>
<div class="content" v-html="content"></div>
<div class="footer" v-show="accessory == '' ? false : true ">
<span>附件:<span class="sub" @click="fileDownLoad"><a-icon type="paper-clip" />{{classify}}附件</span></span>
</div>
</div>
</a-modal>
③
具体代码:重点:初始化编辑器内容
editor.txt.html(this.content)
Markup
<template>
<a-modal
title="新增知识库"
:width="900"
:visible="visible"
:confirmLoading="confirmLoading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-spin :spinning="confirmLoading">
<a-form :form="form">
<a-form-item v-show="false">
<a-input v-decorator="['id']" />
</a-form-item>
<a-form-item
label="标题"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<a-input placeholder="请输入标题" v-decorator="['title', {rules: [{required: true, message: '请输入标题!'}]}]" />
</a-form-item>
<a-form-item
label="来源"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<a-input placeholder="请输入来源" v-decorator="['source', {rules: [{required: true, message: '请输入来源!'}]}]" />
</a-form-item>
<a-form-item
label="摘要"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<a-textarea
placeholder="请输入摘要"
v-decorator="['summary', {rules: [{required: true, message: '请输入摘要!'}]}]"
:auto-size="{ minRows: 3}"
/>
</a-form-item>
<a-form-item
label="类型"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
style="margin-left:-150px;"
>
<a-select
style="width: 100%"
placeholder="请选择类型"
v-decorator="['type', {rules: [{ required: true, message: '请选择类型' }]}]">
<a-select-option v-for="(item,index) in typeData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item
label="封面"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
style="margin-left:-150px;"
>
<!-- <a-input placeholder="请输入封面" v-decorator="['coverimg']" /> -->
<div :key="imgKey">
<a-upload
list-type="picture-card"
:file-list="fileList"
@change="handleChange"
@preview="handlePreview"
:before-upload="beforeImg"
:customRequest="uploadMethod"
>
<div v-if="fileList.length < 1">
<a-icon type="plus" />
<div class="ant-upload-text">
上传封面
</div>
</div>
</a-upload>
</a-upload>
</div>
<a-modal :visible="previewVisible" :footer="null" @cancel="imghandleCancel">
<img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</a-form-item>
<a-form-item
label="内容"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
style="margin-left:-150px;"
>
<div id="editor" style="width:810px;"></div>
<div class="accessory" style="margin-left:-35px;position: relative;">
<span >附件: </span>
<a-upload
:file-list="refileList"
:before-upload="beforeUpload"
:customRequest="fileUpload"
:remove="handleRemove"
>
<a-button v-show="false" style="width: 220px;" id="tiggerPick"> <a-icon type="upload" /> 请选择文件资源 </a-button>
</a-upload>
</div>
</a-form-item>
<!-- <a-form-item
label="附件路径"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
>
<a-input placeholder="请输入附件路径" v-decorator="['filepath']" />
</a-form-item>
<a-form-item
label="排序"
:labelCol="labelCol"
:wrapperCol="wrapperCol"
has-feedback
>
<a-input placeholder="请输入排序" v-decorator="['sort']" />
</a-form-item> -->
</a-form>
</a-spin>
</a-modal>
</template>
<script>
import "@/components/bottomReset.less"
import "@/components/subfile.less"
import { knowledgeBaseEdit } from '@/api/modular/main/knowledgebase/knowledgeBaseManage'
import E from 'wangeditor'
const { BtnMenu } = E
class AlertMenu extends BtnMenu {
constructor(editor) {
// data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
const $elem = E.$(
`<div class="w-e-menu" data-title="上传附件">
<a-button style="width: 40px;height: 40px;">附件</a-button>
</div>`
)
super($elem, editor)
}
// 菜单点击事件
clickHandler() {
// 做任何你想做的事情
document.getElementById("tiggerPick").click();
}
// 菜单是否被激活(如果不需要,这个函数可以空着)
tryChangeActive() {
// 激活菜单
// 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
// 2. this.this.isActive === true
this.active()
}
}
/*封面上传图片预览 */
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
let editor;
export default {
data () {
return {
labelCol: {
xs: { span: 24 },
sm: { span: 5 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 12 },
},
typeData: [],
visible: false,
confirmLoading: false,
form: this.$form.createForm(this),
/*封面上传参数 */
previewImage:'',//预览图片地址
previewVisible:false,//预览
fileList:[],
coverimg:'',//存放封面图片地址
/*附件上传参数 */
refileList:[],
/*富文本内容 */
content:'',
imgKey: '',
// 附件路径
filepath:'',
}
},
mounted(){
},
watch: {
visible() {
if (this.visible) {
this.imgKey = ''
} else {
this.imgKey = Math.random()
}
}
},
methods: {
// 初始化方法
edit (record) {
console.log(record);
this.visible = true
const typeOption = this.$options
this.typeData = typeOption.filters['dictData']('knowledge_type')
if(record.type == 1){
record.type = '危化百科'
}else if(record.type == 2){
record.type = '安全流程'
}else if(record.type == 3){
record.type = '企业安全制度管理模板'
}
setTimeout(() => {
this.form.setFieldsValue(
{
id: record.id,
title: record.title,
source: record.source,
summary: record.summary,
type: record.type,
coverimg: record.coverimg,
content: record.content,
filepath: record.filepath,
sort: record.sort
}
)
}, 100)
this.fileList.push(
{
uid: '-1',
name: 'image.png',
status: 'done',
url: record.coverimg
}
)
this.coverimg = record.coverimg
this.content = record.content
this.filepath = record.filepath
this.refileList.push(
{
uid: '-1',
name: 'file.doc',
status: 'done',
url: record.filepath
}
)
this.$nextTick(() =>{
if (editor==null){
this.initialEditor()
}else {
editor.destroy();//判断编辑器是否被创建,如果创建了就先销毁。
this.initialEditor()
}
})
},
/*富文本编辑器初始化 */
initialEditor(){
// 菜单 key ,各个菜单不能重复
const menuKey = 'alertMenuKey'
editor = new E('#editor')
// editor.txt.clear() //清空富文本的内容
editor.menus.extend(menuKey, AlertMenu)
editor.config.menus.push(menuKey)
editor.config.height = 300
const that = this;
// 图片
editor.config.customUploadImg = function (resultFiles, insertImgFn) {
// resultFiles 是 input 中选中的文件列表
// insertImgFn 是获取图片 url 后,插入到编辑器的方法
console.log(resultFiles[0],'...');
const formData = new FormData();
formData.append('file', resultFiles[0]);
formData.append('type', 'image');
that.axios.post('/sysFileInfo/upload',formData)
.then(res => {
console.log(res);
if(res.success){
// 上传图片,返回结果,将图片插入到编辑器中
insertImgFn(res.data)
}
}).catch(err =>{
})
}
// 视频
editor.config.customUploadVideo = function (resultFiles, insertVideoFn) {
const formData = new FormData();
formData.append('file', resultFiles[0]);
formData.append('type', 'image');
console.log(formData);
that.axios.post('/sysFileInfo/upload',formData)
.then(res => {
if(res.success){
// 上传视频,返回结果,将图片插入到编辑器中
insertVideoFn(res.data)
}
}).catch(err =>{
})
}
editor.config.excludeMenus = ['link']
// 注意,先配置 height ,再执行 create()
editor.create()
editor.txt.html(this.content) // 初始化编辑器内容
},
/*
封面上传
*/
//控制图片预览显示
imghandleCancel() {
this.previewVisible = false;
},
// 在上传之前做出判断
beforeImg(file){
console.log('tupian',file);
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
this.$message.error('只能上传图片文件,请重新上传');
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
return false
}
},
// 上传
uploadMethod(file){
let image = "image"
const formData = new FormData();
formData.append('file', file.file);
formData.append('type', image);
this.axios.post('/sysFileInfo/upload',formData)
.then(res => {
console.log(res);
if(res.success){
this.coverimg = res.data
file.onSuccess();
}
}).catch(err =>{
file.onError() //上传失败
})
},
// 预览
async handlePreview(file) {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
},
handleChange({ fileList }) {
this.fileList = fileList
},
/*附件上传*/
// 移除
handleRemove(file) {
const index = this.refileList.indexOf(file);
const newFileList = this.refileList.slice();
newFileList.splice(index, 1);
this.refileList = newFileList;
},
// 上传之前的限制
beforeUpload(file){
console.log('file',file);
if(this.refileList.length === 0){
this.refileList = [...this.refileList, file];
}else{
this.$message.error('仅支持上传一个文件');
}
},
//上传
fileUpload(){
const formData = new FormData();
if(this.refileList.length){
this.refileList.forEach(file => {
formData.append('file', file);
formData.append('type', 'image');
});
this.axios.post('/sysFileInfo/upload',formData)
.then(res => {
console.log(res);
if(res.success){
this.filepath = res.data
}
}).catch((err => {
this.$message.error('上传失败');
}))
}
},
/**
* 提交表单
*/
handleSubmit () {
const { form: { validateFields } } = this
this.confirmLoading = true
console.log('富文本内容',editor.txt.html());
this.content = editor.txt.html()
validateFields((errors, values) => {
if (!errors) {
for (const key in values) {
if (typeof (values[key]) === 'object') {
values[key] = JSON.stringify(values[key])
}
}
values.coverimg = this.coverimg
values.content = this.content
values.filepath = this.filepath
if(values.type == '危化百科'){
values.type = 1
}else if(values.type == '安全流程'){
values.type = 2
}else if(values.type == '企业安全制度管理模板'){
values.type = 3
}
delete values.createtime
knowledgeBaseEdit(values).then((res) => {
if (res.success) {
this.$message.success('新增成功')
this.confirmLoading = false
this.$emit('ok', values)
this.handleCancel()
} else {
this.$message.error('新增失败')// + res.message
}
}).finally((res) => {
this.confirmLoading = false
})
} else {
this.confirmLoading = false
}
})
},
handleCancel () {
this.form.resetFields()
this.visible = false
this.refileList = []
this.fileList = []
}
}
}
</script>
<style lang="less" scoped>
.accessory-text{
position: absolute;
left: 0;
bottom: 0;
}
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.plus{
font-size: 100px;
color: #dfdfdf;
width: 20px;
height: 20px;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
更多推荐
所有评论(0)