react富文本框组件braft-editor 富文本框添加文件上传服务器

1.首先安装braft-editor 

npm install braft-editor

2.添加富文本框

复制代码
<Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入内容!' }]}
            >
              <BraftEditor
                value={BraftEditor.createEditorState(null)}
                onChange={this.handleChange}
                controls={controls}
                extendControls={extendControls}
                placeholder="请输入正文内容"
              />
</Form.Item>
复制代码

3.添加富文本框功能按钮 其中extendControls是上传图片的按钮,

复制代码
  const controls = [
      'undo',
      'redo',
      'separator',
      'font-size',
      'line-height',
      'letter-spacing',
      'separator',
      'text-color',
      'bold',
      'italic',
      'underline',
      'strike-through',
      'separator',
      'remove-styles',
      'emoji',
      'separator',
      'text-indent',
      'text-align',
      'separator',
      'headings',
      'list-ul',
      'list-ol',
      'separator',
      'link',
      'separator',
      'hr',
      'separator',
      //'media',
      'separator'
    ];
    const extendControls = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <Upload accept="image/*" showUploadList={false} beforeUpload={this.beforeUploadControls}>
            {/* 这里的按钮最好加上type="button",以避免在表单容器中触发表单提交,用Antd的Button组件则无需如此 */}
            <button
              type="button"
              className="control-item button upload-button"
              data-title="插入图片"
            >
              <UploadOutlined />
            </button>
          </Upload>
        )
      }
    ];
复制代码

4.上传的图片和富文本框的内容保存在form表单中,需借助braft-utils组件

npm install braft-utils

 

复制代码
  //上传富文本图片
  beforeUploadControls = (file) => {
    console.log('file', file);
    const index = file.name.lastIndexOf('.');
    const isType = file.name.substr(index + 1).toLowerCase();
    if (isType !== 'jpg' && isType !== 'png') {
      message.error('只支持上传jpg和png格式的图片');
      return true;
    } else {
      if (file.size / (1024 * 1024) > 10 || !file.size) {
        message.error('上传文件不能为空或超过10M');
      } else {
        let formData = new FormData();
        formData.append('file', file);
        //调用后端接口获取图片链接,formData为参数,resouceUpload为自己封装的方法,需换成自己的
        resouceUpload(formData).then((res) => {
          console.log(res);
          if (res.data.code == '0') {
            console.log(this.formRef.current.getFieldValue('content'));
            console.log(ContentUtils);
            if (this.formRef.current.getFieldValue('content')) {
              this.formRef.current.setFieldsValue({
                content: ContentUtils.insertMedias(this.formRef.current.getFieldValue('content'), [
                  {
                    type: 'IMAGE',
                    url: 后端返回的图片的链接
                  }
                ])
              });
            } else {
              this.formRef.current.setFieldsValue({
                content: ContentUtils.insertMedias(BraftEditor.createEditorState(null), [
                  {
                    type: 'IMAGE',
                    url: 后端返回的图片的链接
                  }
                ])
              });
            }
          } else {
            message.error(res.data.message);
          }
        });
      }
    }
  };
  //获取富文本框的内容
  handleChange = (editorState) => {
    const htmlString = editorState.toHTML();
    this.setState({
      editorState: editorState,
      richtext: htmlString
    });
  };
 
复制代码

5.引入文件如下

复制代码
import {
  Button,
  Form,
  Input,
  InputNumber,
  Upload,
} from 'antd';
import { UploadOutlined} from '@ant-design/icons';
import BraftEditor from 'braft-editor';
import { ContentUtils } from 'braft-utils';
import 'braft-editor/dist/index.css';
复制代码

 

posted @   诉诉飞飞  阅读(1718)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示