1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > quill富文本编辑器自定义图片上传

quill富文本编辑器自定义图片上传

时间:2020-07-23 19:57:46

相关推荐

quill富文本编辑器自定义图片上传

github老哥的代码

const editor = new Quill('#quill-editor', {bounds: '#quill-editor',modules: {toolbar: this.toolbarOptions},placeholder: 'Free Write...',theme: 'snow'});/*** Step1. select local image**/function selectLocalImage() {const input = document.createElement('input');input.setAttribute('type', 'file');input.click();// Listen upload local image and save to serverinput.onchange = () => {const file = input.files[0];// file type is only image.if (/^image\//.test(file.type)) {saveToServer(file);} else {console.warn('You could only upload images.');}};}/*** Step2. save to server** @param {File} file*/function saveToServer(file: File) {const fd = new FormData();fd.append('image', file);const xhr = new XMLHttpRequest();xhr.open('POST', 'http://localhost:3000/upload/image', true);xhr.onload = () => {if (xhr.status === 200) {// this is callback data: urlconst url = JSON.parse(xhr.responseText).data;insertToEditor(url);}};xhr.send(fd);}/*** Step3. insert image url to rich editor.** @param {string} url*/function insertToEditor(url: string) {// push image url to rich editor.const range = editor.getSelection();editor.insertEmbed(range.index, 'image', `http://localhost:9000${url}`);}// quill editor add image handlereditor.getModule('toolbar').addHandler('image', () => {selectLocalImage();});

改造成上传到firebase/storage

import firebase from "firebase/app";import "firebase/storage";editor.getModule("toolbar").addHandler("image",(file, editor, cursorLocation, resetUploader) => {const input = document.createElement("input");input.setAttribute("type", "file");input.click();// Listen upload local image and save to serverinput.onchange = () => {const file = input.files[0];console.log(file.type);// file type is only image.if (/^image\//.test(file.type)) {const storageRef = firebase.storage().ref();const docRef = storageRef.child(`documents/blogPostPhotos/${file.name}`);docRef.put(file).on("state_changed",(snapshot) => {console.log(snapshot);},(err) => {console.log(err);},async () => {const downloadURL = await docRef.getDownloadURL();state.quill.insertEmbed(cursorLocation, "image", downloadURL);});} else {console.warn("You could only upload images.");}};});```

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。