经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » React » 查看文章
react quill中图片上传由默认转成base64改成上传到服务器的方法
来源:jb51  时间:2019/10/30 11:45:24  对本文有异议

使用react-quill富文本编辑器,里面处理图片是默认转成base64,提交到后台的时候文件太大,因此这里改写处理image的逻辑,改成上传到服务器。

具体代码如下:

配置1

  1. import Quill from 'quill'
  2. import ReactQuill from 'react-quill'
  3. import 'react-quill/dist/quill.core.css'
  4. import 'react-quill/dist/quill.snow.css'
  5. import QuillEmoji from 'quill-emoji'
  6. import 'quill-emoji/dist/quill-emoji.css'
  7.  
  8. Quill.register({
  9. 'modules/emoji-toolbar': QuillEmoji.ToolbarEmoji,
  10. // 'modules/emoji-textarea': QuillEmoji.TextAreaEmoji,
  11. 'modules/emoji-shortname': QuillEmoji.ShortNameEmoji
  12. })
  13.  
  14. const toolbarContainer = [
  15. [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
  16. [{ 'font': [] }],
  17. [{ 'header': 1 }, { 'header': 2 }], // custom button values
  18. ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  19. [{ 'align': [] }],
  20. [{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
  21. [{ 'direction': 'rtl' }], // text direction
  22. [{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
  23. ['blockquote', 'code-block'],
  24.  
  25. [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  26. [{ 'color': [] }, { 'background': [] }],
  27. ['emoji', 'image', 'video', 'link'],
  28.  
  29. ['clean']
  30. ]
  31.  

配置2

  1. <ReactQuill
  2. ref={ref => this.quillRef = ref}
  3. placeholder="填写活动详情~"
  4. theme="snow"
  5. value={this.state.detailTpl}
  6. onChange={this.handleChangeDetail}
  7. modules={{
  8. toolbar: {
  9. container: toolbarContainer,
  10. handlers: {
  11. image: this.imageHandler
  12. }
  13. },
  14. 'emoji-toolbar': true,
  15. // 'emoji-textarea': true,
  16. 'emoji-shortname': true,
  17. }}
  18. />

图片处理方法

  1. imageHandler = () => {
  2. this.quillEditor = this.quillRef.getEditor()
  3. const input = document.createElement('input')
  4. input.setAttribute('type', 'file')
  5. input.setAttribute('accept', 'image/*')
  6. input.click()
  7. input.onchange = async () => {
  8. const file = input.files[0]
  9. const formData = new FormData()
  10. formData.append('quill-image', file)
  11. const res = await uploadFile(formData)
  12. const range = this.quillEditor.getSelection()
  13. const link = res.data[0].url
  14.  
  15. // this part the image is inserted
  16. // by 'image' option below, you just have to put src(link) of img here.
  17. this.quillEditor.insertEmbed(range.index, 'image', link)
  18. }
  19. }
  20.  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号