引言:
富文本编辑器传图片会解码成64位,非常长导致数据库会报错 第一种方法:将数据库类型改成 mediumtext
第二种办法:本文中的方法
说明,本周文所用语法糖为Vue3 setup语法,即<script setup>
思路
拦截富文本编辑器上传图片功能,即点击按钮将事件绑定到input
或upload
的上传图片上 将图片上传到自己服务器,并返回url地址 将url地址存到数据库,显示的时候直接映射
第一步:安装 quill-image-extend-module
npm install quill- image- extend- module -- save- dev
第二部:全局注册 main.js
import { QuillEditor, Quill } from '@vueup/vue-quill'
import '@vueup/ vue- quill/ dist/ vue- quill. snow. css';
import { container, QuillWatch, ImageExtend} from "quill-image-extend-module" ;
Quill. register ( 'modules/ImageExtend' , ImageExtend) const app = createApp ( App)
app. component ( 'QuillEditor' , QuillEditor)
第三步:组件引用 (引入我的部分代码,不相关部分已去除)
< template> < QuillEditorv- model: content= "form.productParaImgs" contentType= "html" theme= "snow" ref= "productParaImgsForm" : options= "productParaImgsEditorOption" @change= "onEditorChange($event)" style= "height:200px" > < / QuillEditor> < inputtype= "file" accept= ".png,.jpg,.jpeg" @change= "productParaImgsChange" id= "productParaImgsUpload" style= "display: none;border: 4px solid red" / >
< / template> < script setup>
import { container, ImageExtend, QuillWatch} from 'quill-image-extend-module'
const productParaImgsForm = ref ( null) ;
const productParaImgsEditorOption = ref ( { placeholder: "请输入" , theme: "snow" , modules: { ImageExtend: { name: 'img' , size: 3 , action: '' , response: ( res) = > { } , headers: ( xhr) = > { xhr. setRequestHeader ( 'token' , window. sessionStorage. getItem ( 'token' ) ) } , } , toolbar: { container: container, handlers: { 'image' : function ( value) { if ( value) { document. querySelector ( "#productParaImgsUpload" ) . click ( ) ; } else { this. quill. format ( "image" , false) ; } } } } }
} )
const productParaImgsChange = async ( e) = > {
let formData = new FormData ( ) ; let file = e. target. files[ 0 ] ; formData. append ( 'file' , file) ; let result = await requestUitl. post ( "/sys/product/uploadImage" , formData) ; if ( result. data. code == 647 ) { let quill = productParaImgsForm. value. getQuill ( ) let length = quill. getSelection ( ) . index; quill. insertEmbed ( length, "image" , getServerUrl ( ) + result. data. src) ; quill. setSelection ( length + 1 ) ; }
}
< / script>
后端返回类型参考
Map< String, Object> dataMap = new HashMap< > ( ) ;
dataMap. put ( "title" , newFileName) ;
dataMap. put ( "src" , "image/product/" + newFileName) ;
请求封装参考
export function post ( url, params = { } ) { return new Promise ( ( resolve, reject) = > { httpService ( { url: url, method: 'post' , data: params} ) . then ( response = > { resolve ( response) ; } ) . catch ( error = > { reject ( error) ; } ) ; } ) ;
}
export default { post, getServerUrl
}