Vue+CKeditor+自定义CKFinder图片上传

2019-10-04  本文已影响0人  芸芸众生ing

资料文档:https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html#the-complete-implementation

<template>
  <!--  这个不用说也知道吧 -->
  <textarea id="editor" ref="editor"></textarea>
</template>

<script>
// 引入必须文件
import CKeditor from "@ckeditor/ckeditor5-build-classic";
// 编辑器工具栏文本语言 zh-cn 是简体中文
import "@ckeditor/ckeditor5-build-classic/build/translations/zh-cn";
export default {
  data() {
    return {
      editorOption: {
        value: null
      }
    };
  },
  mounted() {
    this.initCkeditor();
  },
  methods: {
    initCkeditor() {
      let that = this;

      // 上传适配插件所有的操作都在这里面完成
      class myUploadLoader {
        constructor(loader) {
          this.loader = loader;
        }
        upload() {
          return this.loader.file.then(file =>new Promise((resolve, reject) => {

      //方法一:
                let reader = new FileReader();
                reader.addEventListener(
                  "load",
                  function() {
                    console.log(reader.result);//这里是base64路径。
                    resolve({
                      default: reader.result
                    });
                  },
                  false
                );
                reader.readAsDataURL(file);

  //方法二:
                // 这里面写的就是上传请求,只需要最终结果调用 resolve 方法
                // 并且返回一个至少包含 default : imgUrl 的对象,
                // 例如:{default:'http://abc.com/a/b.png'}
                let formdata = new FormData();
                formdata.append('file',file);
                fetch(url,{
                  method:'post',
                  body:formdata
                })
                .then(response=>{
                  // 后端至少返回上传图片的URL
                  let url = response.url
                  resolve({
                    default: url
                  });
                })
                .catch(err=>{
                  reject(err)
                })
              })
          );
        }
        abort() {}
      }
      function myUpload(e) {
        // 使用 CKeditor 提供的 API 修改上传适配器
        e.plugins.get("FileRepository").createUploadAdapter = loader => new myUploadLoader(loader);
      }
      // 构建编辑器
      CKeditor.create(this.$refs.editor, {
        // 编辑器配置
        extraPlugins: [myUpload], // 添加自定义图片上传适配插件
        language: "zh-cn"
      })
        .then(e => {
          // 每次修改都会触发更新 vm.data 里面的属性值
          e.model.document.on("change:data", () => {
            that.editorOption.value = e.getData();
          });
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  destroyed() {
    this.editor.destroy().catch(err => {
      console.log(err);
    });
  }
};
</script>

<style>
</style>
上一篇 下一篇

猜你喜欢

热点阅读