添加自定义标题以上传图片

时间:2018-10-18 11:49:58

标签: ckeditor ckeditor5

我目前正在尝试将CKeditor 5 ReactComponent集成到我的应用中。

我在上传图片功能方面遇到了问题...我使用的是Node / Express后端,该后端使用JWT身份验证中间件,因此每个请求都必须具有Authorization标头才能通过。

我想知道以下情况之一是否可能:

  • 向组件添加自定义标头的方法
  • 一种覆盖上传处理程序并调用自定义处理程序的方法,而我可以做任何事情

下面是我的代码

<CKEditor
  editor={ClassicEditor}
  data="<p>Add product description here</p>"
  onInit={(editor) => {
    // You can store the "editor" and use when it is needed.
    //console.log('Editor is ready to use!', editor);
  }}
  onChange={(event, editor) => {
    const data = editor.getData();
    this.handleData(data)
  }}
  config={{
    ckfinder: {
      uploadUrl: `${apiUrl}/upload/images/description`,
    },
  }}
/>

谢谢

1 个答案:

答案 0 :(得分:1)

在属性onInit中尝试使用此代码

onInit={ editor => {
 editor.plugins.get( 'FileRepository' ).createUploadAdapter = function( loader ) {
  return new UploadAdapter( loader );
 };
}}

必须创建类UploadAdapter之后

class UploadAdapter {
  constructor( loader ) {
    // Save Loader instance to update upload progress.
    this.loader = loader;
  }

  upload() {
    const data = new FormData();
    data.append('typeOption', 'upload_image');
    data.append('file', this.loader.file);

    return new Promise((resolve, reject) => {
      axios({
        url: `${API}forums`,
        method: 'post',
        data,
        headers: {
          'Authorization': tokenCopyPaste()
        },
        withCredentials: true
      }).then(res => {
        console.log(res)
        var resData = res.data;
        resData.default = resData.url;
        resolve(resData);
      }).catch(error => {
        console.log(error)
        reject(error)
      });
    });
  }

  abort() {
    // Reject promise returned from upload() method.
  }
}