vue---tinymce粘贴图片【完美解决】

最近在优化一个前端开发框架,做好的系统,存在大量的图片上传,特别是富文本里面的图片,上传多个,很麻烦,运营说如果能够复制粘贴板的图片,就可以截图上传,就很方便了。

考虑到运营小姐姐的需求,我就花了半个小时开发了这样的一个功能。

第一步:配置粘贴【paste】具体配置项

tinymce.init({
  selector: '#tinydemo',
  plugins: 'paste',
  toolbar: 'paste',
  paste_data_images: true // 默认是false的,记得要改为true才能粘贴
})

到此,复制图片的功能就已经完成了。

但是,检查代码发现,复制过来的图片,在富文本里面是base64位的,这种不行,需要调整为上传图片,返回图片路径后插入。

第二步:配置图片上传函数

此函数为:images_upload_handler

示例代码:

images_upload_handler(blobInfo, success, failure, progress) {
  progress(0);
  const token = _this.$store.getters.token;
  getToken(token).then(response => {
    const url = response.data.qiniu_url;
    const formData = new FormData();
    formData.append('token', response.data.qiniu_token);
    formData.append('key', response.data.qiniu_key);
    formData.append('file', blobInfo.blob(), url);
    upload(formData).then(() => {
      success(url);
      progress(100);
    })
  }).catch(err => {
    failure('出现未知问题,刷新页面,或者联系程序员')
    console.log(err);
  });
}

结合项目,我的代码:

// 复制粘贴图片 需先上传服务器
images_upload_handler(blobInfo, success, failure, progress){
  // let url = "/uploads/image/20220908/155f0d639c282ecad9b4e21c4b08ce0c.png";
  // success(url);
  // console.log(blobInfo.blob()); // blob对象
  // console.log(blobInfo.base64()); // base64对象
  let that = this;
  let formData = new FormData();
  formData.append('file',blobInfo.blob(),"DX.jpg");
  uploadImg(formData).then(res => {
    let path = imgURL + res.data;
    success(path);
  }).catch(error => {
    that.$message.error('上传图片失败');
  });
}

到此,复制图片上传就完成了。

参考:

https://blog.csdn.net/Jioho_chen/article/details/118252638

打完收工!

posted @ 2022-09-08 11:20  帅到要去报警  阅读(2930)  评论(0编辑  收藏  举报