
编辑器配置图片上传,调用后端接口服务
看代码
<quill-editor ref="quilRef" v-model:content="form.pushContent2" :options="editorOption"
contentType="html" />
//隐藏上传图片
<input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileChange">
js部分
<script lang="ts" setup>
import axios from 'axios'
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css'; // 引入样式文件
const fileInput = ref(null)
const uploadUrl = '你的上传接口路径'
const editorOption = {
theme: 'snow',
modules: {
history: {
delay: 0,
maxStack: 0
},
toolbar: {
container: [
[{ 'size': ['small', false, 'large'] }],
[{ 'color': [] }],
[{ 'list': 'bullet' }],
['bold', 'italic', 'underline'],
['image', 'link']
],
handlers: {
image: () => fileInput.value.click()
}
}
},// 自定义编辑器内的空白处理样式
customOptions: {
whitespace: 'pre-wrap'
}
};
//上传图片
const handleFileChange = async (e) => {
const file = e.target.files[0]
if (!file) return
try {
const formData = new FormData()
formData.append('file', file)
formData.append('prefix', 'image')
const res = await axios.post(uploadUrl, formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
if (res.data.url) {
insertImage(res.data.url)
}
} catch (error) {
console.error('Upload failed:', error)
} finally {
e.target.value = '' // 重置input
}
}
//向富文本插入图片
const insertImage = (url) => {
const quill = quilRef.value.getQuill()
const range = quill.getSelection()
quill.insertEmbed(range.index, 'image', url)
quill.setSelection(range.index + 1)
}
</script>