braft-editor上传图片,上传到七牛云

757 阅读1分钟

需求:因为有使用braft-editor富文本框,然后因为默认是传base64,然后如果图片稍微过大,后台字段存不住了,所以改成上传返回地址后,拿到地址在重新去请求保存接口或者编辑接口 所以根据官方文档的方法,直接去调就可以,

1、给出# braft-editor的api文档方法:www.yuque.com/braft-edito…

2、我的思路是参照这个大佬的 稍微跟他的不同,我的是还需要上传七牛云 这位大佬的文章地址:www.jianshu.com/p/acb0fc96b…

3、下面是我的代码 ``

 // 上传-我这只上传图片
 // 上传七牛云需要的参数有三个  file  key  token 
 // file 是上传的文件,key是文件的名称 token是七牛云那边的token
 // 5.由于图片上传、视频上传项目中都是单独走的接口,需要一个上传的方法
  const myUploadFn = async (param) => {

    const serverURL = 'https://up.qbox.me/' // upload 是接口地址
    const xhr = new XMLHttpRequest();
    const fd = new FormData();
    const token = await dispatch({ type: 'common/getQiniuToken' });// 获取七牛图片token

    const successFn = (response) => {
      // console.log(response,'response')
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      // console.log('xhr.responseText', xhr.responseText);
      // 下面是返回的地址,如果不全就要自己去拼接
      param.success({
        url: 'https:/xxxxxx.com/'+JSON.parse(xhr.responseText).key,
      })
    };

    const progressFn = (event) => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100)
    };

    const errorFn = (response) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: '上传失败'
      })
    };
    // getRandomStr 某方法随机12位字符串
    const key = getRandomStr(12) + new Date().getTime();
    const name = param.file.name;
    const index = name.lastIndexOf('.');
    const suffix = name.substring(index + 1, name.length)

    xhr.upload.addEventListener("progress", progressFn, false);
    xhr.addEventListener("load", successFn, false);
    xhr.addEventListener("error", errorFn, false);
    xhr.addEventListener("abort", errorFn, false);
    fd.append('file', param.file);
    xhr.open('POST', serverURL, true);
    fd.append('token', token);
    fd.append('key', `${key}.${suffix}`);
    xhr.send(fd)

  };


// 底部部分
  return (
    <div>
        <BraftEditor 
            value={editorState} 
            onChange={handleEditorChange} 
            ref={braftEditorRef} 
            media={{uploadFn: myUploadFn}}
        />
    </div>
  );