使用vue-quill-editor圖片上傳

問題描述:html

   環境:webpack+vue+elementvue

  vue-quill-editor插入圖片的方式是將圖片轉爲base64再放入內容中,直接存儲數據庫會致使內容過多佔用大量的數據庫存儲空間,加載速度也會變慢,此方法是將圖片上傳到七牛返回到編輯器中,java

解決方法webpack

1.html內容  配合element-ul的上傳組件  git

apiurl是後臺接口地址 
 <el-form-item label="項目簡介">
                     <div  v-loading="imageLoading"
                        element-loading-text="請稍等,圖片上傳中">
                        <quill-editor  ref="newEditor"  v-model="form.intro" ></quill-editor>
                        <!-- 文件上傳input 將它隱藏-->
                            <el-upload style="display:none"  :action="apiurl" :show-file-list="false" :before-upload='newEditorbeforeupload'  :on-success='newEditorSuccess'
                            ref="uniqueId" id="uniqueId">
                            </el-upload >
                        </div>
                </el-form-item>

2.javascrpitgithub

  vue實例化是在mounted註冊修改原來的圖片上傳事件web

  mounted(){
                var imgHandler = async function(state) {
                    if (state) {
                    var fileInput =document.querySelector('#uniqueId input') //隱藏的file元素
                     fileInput.click() //觸發事件
                    }
                }
               this.$refs.newEditor.quill.getModule("toolbar").addHandler("image", imgHandler)  
            
                },
              

 

methods:添加方法便可
                 newEditorbeforeupload(file){                       
                         const isJPG = file.type === 'image/jpeg' ||file.type ===  'image/png';
                        const isLt2M = file.size / 1024 / 1024 < 2;
                        if (!isJPG) {
                            this.$message.error('上傳圖片只能是 JPG或PNG 格式!');
                        }
                        if (!isLt2M) {
                            this.$message.error('上傳圖片大小不能超過 2MB!');
                        }
                    if(isJPG && isLt2M)this.imageLoading =true
                         return isJPG && isLt2M;                                            
                },
                    //上傳圖片回調 
                newEditorSuccess(response, file, fileList){
                    if(response.status===1){                        
                        this.addImgRange = this.$refs.newEditor.quill.getSelection()
                        this.$refs.newEditor.quill.insertEmbed(this.addImgRange != null?this.addImgRange.index:0, 'image',response.datas, Quill.sources.USER)
                    }
                  this.imageLoading =false
                },

 

 

 

 

 ps:ue-quill-editor是基於適用於Vue2的富文本編輯器   github地址
相關文章
相關標籤/搜索