使用vue-quill-editor图片上传
问题描述:
环境:webpack+vue+element
vue-quill-editor插入图片的方式是将图片转为base64再放入内容中,直接存储数据库会导致内容过多占用大量的数据库存储空间,加载速度也会变慢,此方法是将图片上传到七牛返回到编辑器中,
解决方法
1.html内容 配合element-ul的上传组件
apiurl是后台接口地址
<el-form-item label="项目简介">
<div v-loading="imageLoading"
element-loading-text="请稍等,图片上传中">
<quill-editor ref="newEditor" v-model="form.intro" ></quill-editor>
<!-- 文件上传input 将它隐藏-->
<el-upload style="display:none" :action="apiurl" :show-file-list="false" :before-upload='newEditorbeforeupload' :on-success='newEditorSuccess'
ref="uniqueId" id="uniqueId">
</el-upload >
</div>
</el-form-item>
2.javascrpit
vue实例化是在mounted注册修改原来的图片上传事件
mounted(){
var imgHandler = async function(state) {
if (state) {
var fileInput =document.querySelector('#uniqueId input') //隐藏的file元素
fileInput.click() //触发事件
}
}
this.$refs.newEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
},
methods:添加方法即可
newEditorbeforeupload(file){ const isJPG = file.type === 'image/jpeg' ||file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传图片只能是 JPG或PNG 格式!'); } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB!'); } if(isJPG && isLt2M)this.imageLoading =true return isJPG && isLt2M; }, //上传图片回调 newEditorSuccess(response, file, fileList){ if(response.status===1){ this.addImgRange = this.$refs.newEditor.quill.getSelection() this.$refs.newEditor.quill.insertEmbed(this.addImgRange != null?this.addImgRange.index:0, 'image',response.datas, Quill.sources.USER) } this.imageLoading =false },

ps:ue-quill-editor是基于适用于Vue2的富文本编辑器 github地址

浙公网安备 33010602011771号