react quillの画像アップロードはデフォルトからbase 64に変更されてサーバーにアップロードする方法です。
react-quillリッチテキストエディタを使って、中の処理画像はデフォルトでbase 64になり、バックグラウンドに提出する時はファイルが大きすぎるので、ここでイメージを処理するロジックを書き換えて、サーバーにアップロードするようになりました。
具体的なコードは以下の通りです。
設定1
具体的なコードは以下の通りです。
設定1
import Quill from 'quill'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.core.css'
import 'react-quill/dist/quill.snow.css'
import QuillEmoji from 'quill-emoji'
import 'quill-emoji/dist/quill-emoji.css'
Quill.register({
'modules/emoji-toolbar': QuillEmoji.ToolbarEmoji,
// 'modules/emoji-textarea': QuillEmoji.TextAreaEmoji,
'modules/emoji-shortname': QuillEmoji.ShortNameEmoji
})
const toolbarContainer = [
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'font': [] }],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
['bold', 'italic', 'underline', 'strike'], // toggled buttons
[{ 'align': [] }],
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
['blockquote', 'code-block'],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'color': [] }, { 'background': [] }],
['emoji', 'image', 'video', 'link'],
['clean']
]
設定2
<ReactQuill
ref={ref => this.quillRef = ref}
placeholder=" ~"
theme="snow"
value={this.state.detailTpl}
onChange={this.handleChangeDetail}
modules={{
toolbar: {
container: toolbarContainer,
handlers: {
image: this.imageHandler
}
},
'emoji-toolbar': true,
// 'emoji-textarea': true,
'emoji-shortname': true,
}}
/>
画像処理方法
imageHandler = () => {
this.quillEditor = this.quillRef.getEditor()
const input = document.createElement('input')
input.setAttribute('type', 'file')
input.setAttribute('accept', 'image/*')
input.click()
input.onchange = async () => {
const file = input.files[0]
const formData = new FormData()
formData.append('quill-image', file)
const res = await uploadFile(formData)
const range = this.quillEditor.getSelection()
const link = res.data[0].url
// this part the image is inserted
// by 'image' option below, you just have to put src(link) of img here.
this.quillEditor.insertEmbed(range.index, 'image', link)
}
}
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。