一、背景描述
使用插件时,用默认的图片上传操作, 图片经过转码后字节过大, 后端可能会保存失败
二、解决办法
使用element 的上传组件, 重写富文本默认的上传事件; 触发element的上传, 拿到上传后的文件信息,将此存在云端上。 利用云端给出的地址给quill-editor 赋值并传给后端。
三、代码
- 安装依赖
npm install vue-quill-editor --save
npm install quill-image-resize-module --save
- 项目引用
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillEditor from 'vue-quill-editor';
import * as Quill from 'quill' // 引入编辑器
import ImageResize from 'quill-image-resize-module';
Quill.register('modules/imageResize',ImageResize);
Vue.use(quillEditor)
- 添加vue.config.js文件配置
module.exports = {
chainWebpack: config => {
config.plugin("provide").use(webpack.ProvidePlugin, [
{
"window.Quill": "quill/dist/quill.js",
Quill: "quill/dist/quill.js"
}
]);
}
};
- 使用
<el-upload
v-show="false"
class="upload-demo"
action="/api/upload/file"
accept="image/jpeg,image/png,image/bmp"
:before-upload="handleBeforeUpload"
:on-success="handleSuccess"
:show-file-list="false"
>
<el-button v-show="false" class="ivu-btn"></el-button>
</el-upload>
<quill-editor
ref="QuillEditor"
v-model="contain"
:options="editorOption"
>
</quill-editor>
//script
data() {
return {
contain:"",
editorOption: {
placeholder: "请输入...",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
[{ color: [] }, { background: [] }],
["link", "image"],
["blockquote", "code-block"],
[{ align: [] }],
[{ list: "ordered" }, { list: "bullet" }],
[{ script: "sub" }, { script: "super" }],
[{ header: 1 }, { header: 2 }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ size: ["small", false, "large", "huge"] }],
[{ font: [] }],
[{ indent: '-1' }, { indent: '+1' }],
],
handlers: {
image: function (value) {
if (value) {
// 调用element图片上传
document.querySelector(".ivu-btn").click();
} else {
this.quill.format("image", false);
}
},
},
}, // 工具栏功能
imageResize: {
displayStyles: {
backgroundColor: "black",
border: "none",
color: "white",
},
modules: ["Resize", "DisplaySize", "Toolbar"],
},
},
},
}
}
methods:{
handleBeforeUpload(file) {
// 检验文件类型
const isIMAGE =
file.type === "image/jpeg" ||
file.type === "image/png" ||
file.type === "image/bmp";
if (!isIMAGE) {
this.$message.error(`请上传图片类型文件!`);
return false;
}
// 校检文件大小
const isLt = file.size / 1024 / 1024 < this.fileSize;
if (!isLt) {
this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
return false;
}
return true;
},
handleSuccess(res) {
// 获取富文本组件实例
let quill = this.$refs.QuillEditor.quill;
// 如果上传成功,801是后端返回的成功的码值
if (res.code === 801) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(
length,
"image",
addressUrl.HTTP_URI + res.data.filePath
); //第三个参数拼接的是图片的完整可访问地址
// 调整光标到最后
quill.setSelection(length + 1);
} else {
// 提示信息,需引入Message
this.$message.error("图片插入失败");
}
},
}