就是要一个富文本编辑器,然后有图片上传功能,因为vue-quill-editor是将图片转为base64编码,所以当图片比较大时,提交后台时参数过长,导致提交失败。
vue-quill-editor引入过程略
废话不多说,上代码
1.引入element的图片上传组件:
<el-upload
class="avatar-uploader2"
:show-upload-list="false"
:on-success="uploadSuccess"
:before-upload="beforeAvatarUpload"
type="drag"
:action="uploadUrl">
</el-upload>
2.上传前以及上传成功的方法:
// 上传图片前 // 上传前对图片文件的类型及大小的判断
beforeAvatarUpload (file) {
var fileName=new Array()
fileName =file.name.split('.');
const extension = fileName[fileName.length-1] === 'jpg'
const extension2 = fileName[fileName.length-1]=== 'png'
const extension1 = fileName[fileName.length-1]=== 'gif'
const isLt2M = file.size / 1024 / 1024 < 10
if (!extension && !extension2) {
this.$message({
message: '只能上传jpg/png/gif格式图片!',
type: 'warning'
});
return false;
}
if (!isLt2M) {
this.$message({
message: '上传图片大小不能超过 10MB!',
type: 'warning'
});
return false;
}
return extension || extension2||extension1 && isLt2M
},
// 上传图片成功
uploadSuccess(res, file) {
// res为图片服务器返回的数据
// 获取富文本组件实例
let quill = this.$refs.myQuillEditor.quill;
// 如果上传成功
if (res.code == 0) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片 res.data.url为服务器返回的图片地址
quill.insertEmbed(length,'image',res.data.src)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
this.$message.error('图片插入失败')
}
// loading动画消失
this.quillUpdateImg = false
},
3.定义工具栏,写在<script>标签的第一行
// 工具栏配置
const toolbarOptions = [ ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
["blockquote", "code-block"], // 引用 代码块
[{header: 1}, {header: 2}], // 1、2 级标题
[{list: "ordered"}, {list: "bullet"}], // 有序、无序列表
[{script: "sub"}, {script: "super"}], // 上标/下标
[{indent: "-1"}, {indent: "+1"}], // 缩进
// [{'direction': 'rtl'}], // 文本方向
[{size: ["small", false, "large", "huge"]}], // 字体大小
[{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
[{color: []}, {background: []}], // 字体颜色、字体背景颜色
[{font: []}], // 字体种类
[{align: []}], // 对齐方式
["clean"], // 清除文本格式
["link", "image", "video"] // 链接、图片、视频
];
4.重写点击图片按钮事件 代码为:
editorOption: {
placeholder: '',
theme: 'snow',
modules: {
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
'image': function (value) {
if (value) {
// 触发input框选择图片文件
document.querySelector('.avatar-uploader2 input').click()
} else {
this.quill.format('image', false);
}
}
}
}
}
},
到此,图片上传改为上传到服务器修改完成,点击图片的icon的时候,文本编辑器最后存储的是服务器返回的url地址