Vue+Vite+TS quill-editor粘贴图片上传并删除原图片

Vue+Vite+TS quill-editor粘贴图片上传并删除原图片

近期项目中富文本编辑器 quill-editor需要支持复制图片上传,代码如下:

<template>
  <div>
    <div class="editor">
      <quill-editor ref="quillEditorRef" v-model:content="content" contentType="html"
        @textChange="(e) => $emit('update:modelValue', content)" :options="options" :style="styles" />
    </div>
  </div>
</template>
<script>
import { QuillEditor, Quill } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
// 上传的图片服务器地址
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/system/oss/upload");
const headers = ref({ Authorization: "Bearer " + getToken() });
const quillEditorRef = ref();

// 上传图片的函数
function uploadImage(blob) {
  // 创建FormData
  const formData = new FormData();
  formData.append('file', blob);
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  // 使用fetch或者其他Ajax库上传图片
  fetch(baseUrl + '/system/oss/upload', {
    method: 'POST',
    body: formData,
    headers: {
      Authorization: "Bearer " + getToken()
    }
  }).then(response => response.json())
    .then(data => {
      let quill = toRaw(quillEditorRef.value).getQuill();
      const imageUrl = baseUrl + data.data.url;
      // 删除原图片
      quill.deleteText(quill.getSelection().index - 1, 1)
      // 在Quill中插入上传之后的图片
      quill.insertEmbed(quill.getSelection().index, 'image', imageUrl);
    })
    .catch(error => {
      console.error('Upload failed', error);
    });
}
// 复制图片粘贴上传
function init() {
  let quill = toRaw(quillEditorRef.value).getQuill();
  // 粘贴事件
  quill.root.addEventListener("paste", (evt) => {
    const clipboardData = event.clipboardData || window.clipboardData;
    console.log(clipboardData)
    if (clipboardData) {
      const items = clipboardData.items;
      if (items && items.length > 0) {
        for (let i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            const blob = items[i].getAsFile();
            uploadImage(blob);
          }
        }
      }
    }
  })
}
onMounted(() => {
  init()
})
</script>

inith()方法中“let quill = toRaw(quillEditorRef.value).getQuill()"获取当前富文本编辑器;
quill.root.addEventListener(“paste”, (evt) => {})触发粘贴事件;”quill.deleteText(quill.getSelection().index - 1, 1)“删除原图片;”quill.insertEmbed(quill.getSelection().index, ‘image’, imageUrl);“插入上传成功的图片;
init()方法需要放在dom元素创建完成的”onMounted中“。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuwenwenwenwenyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值