公司的项目中有用到富文本quill-editor组件,上传图片时会返回base64路径,传给后端需要将base64转为链接传过去
使用如下:
1.用elementui的上传组件,使用v-show="false"隐藏
<div class="edit_container">
<el-upload class="avatar-uploader"
v-show="false"
action="String" name="file"
:show-file-list="false"
:http-request="httpRequest"
:before-upload="beforeAvatarUpload">
</el-upload>
<quill-editor v-model="content"
ref="myQuillEditor"
:options="editorOption"
>
</quill-editor>
</div>
2.在data中的定义
data{
editorOption: {
placeholder: '',
modules:{
toolbar: {
container: toolbarOptions,
handlers: {
image: function (value) {
if (value) {
// 调用element的图片上传组件
document.querySelector('.avatar-uploader input').click()
} else {
this.quill.format('image', false)
}
}
}
}
},
},
}
3.在图片上传成功后将链接插入
methods:{
httpRequest(param) {
let formData = new FormData();
formData.append('file', param.file);
formData.append('FileName', param.file.name);
console.log(formData.get('file'));
this.$request({
method: 'POST',
url: UPLOAD_IMG,
data: formData
}).then((res) => {
let imgurl = res.jsonResult.object[0].file_url;
// console.log(imgurl,'imgurl---',res);
let quill = this.$refs.myQuillEditor.quill
// 如果上传成功
if (res.jsonResult.status === 100) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(length, 'image', imgurl)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
// 提示信息,需引入Message
this.$message.error('图片插入失败!')
}
});
},
beforeAvatarUpload(file) {
console.log(file, 'file');
let flag = ['png', 'jpeg'].includes(file.type.split('/')[1]);
const isLt2M = file.size / 1024 / 1024 < 5;
if (!flag) {
this.$message.error('上传图片格式是 JPG 或 PNG 格式!');
}
if (!isLt2M) {
this.$message.error('图片大小不能超过 5MB!');
}
return flag && isLt2M;
},}