VUE項目富文本編輯器VUE-QUILL-EDITOR之自定義圖片上傳

使用富文本編輯器的第一步肯定是先安裝依賴 npm i vue-quill-editor

1、如果按照官網富文本編輯器中的圖片上傳是將圖片轉爲base64格式的,如果需要上傳圖片到自己的服務器,需要修改配置。

    創建一個quill-config.js的文件,裏面寫自定義圖片上傳。代碼如下

/*富文本編輯圖片上傳配置*/
const uploadConfig = {
    action:  '',  // 必填參數 圖片上傳地址
    methods: 'POST',  // 必填參數 圖片上傳方式
    token: '',  // 可選參數 如果需要token驗證,假設你的token有存放在sessionStorage
    name: 'img',  // 必填參數 文件的參數名
    size: 500,  // 可選參數   圖片大小,單位爲Kb, 1M = 1024Kb
    accept: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon'  // 可選 可上傳的圖片格式
};

// toolbar工具欄的工具選項(默認展示全部)
const toolOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],
    [{'indent': '-1'}, {'indent': '+1'}],
    [{'direction': 'rtl'}],
    [{'size': ['small', false, 'large', 'huge']}],
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],
    [{'font': []}],
    [{'align': []}],
    ['clean'],
    ['link', 'image', 'video']
];
const handlers = {
    image: function image() {
        var self = this;

        var fileInput = this.container.querySelector('input.ql-image[type=file]');
        if (fileInput === null) {
            fileInput = document.createElement('input');
            fileInput.setAttribute('type', 'file');
            // 設置圖片參數名
            if (uploadConfig.name) {
                fileInput.setAttribute('name', uploadConfig.name);
            }
            // 可設置上傳圖片的格式
            fileInput.setAttribute('accept', uploadConfig.accept);
            fileInput.classList.add('ql-image');
            // 監聽選擇文件
            fileInput.addEventListener('change', function () {
                // 創建formData
                var formData = new FormData();
                formData.append(uploadConfig.name, fileInput.files[0]);
                formData.append('object','product');
                // 如果需要token且存在token
                if (uploadConfig.token) {
                    formData.append('token', uploadConfig.token)
                }
                // 圖片上傳
                var xhr = new XMLHttpRequest();
                xhr.open(uploadConfig.methods, uploadConfig.action, true);
                // 上傳數據成功,會觸發
                xhr.onload = function (e) {
                    if (xhr.status === 200) {
                        var res = JSON.parse(xhr.responseText);
                        let length = self.quill.getSelection(true).index;
                        //這裏很重要,你圖片上傳成功後,img的src需要在這裏添加,res.path就是你服務器返回的圖片鏈接。            
                        self.quill.insertEmbed(length, 'image', res.path);
                        self.quill.setSelection(length + 1)
                    }
                    fileInput.value = ''
                };
                // 開始上傳數據
                xhr.upload.onloadstart = function (e) {
                    fileInput.value = ''
                };
                // 當發生網絡異常的時候會觸發,如果上傳數據的過程還未結束
                xhr.upload.onerror = function (e) {
                };
                // 上傳數據完成(成功或者失敗)時會觸發
                xhr.upload.onloadend = function (e) {
                    // console.log('上傳結束')
                };
                xhr.send(formData)
            });
            this.container.appendChild(fileInput);
        }
        fileInput.click();
    }
};

export default {
    placeholder: '',
    theme: 'snow',  // 主題
    modules: {
        toolbar: {
            container: toolOptions,  // 工具欄選項
            handlers: handlers  // 事件重寫
        }
    }
};

 

 

然後在需要引入富文本編輯器的頁面引入

 

<template>
  <div id="Test">
    <quill-editor ref="myTextEditor"
              v-model="content" :options="quillOption">
    </quill-editor>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import quillConfig from './quill-config.js'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      content: '<h2>hello quill-editor</h2>',
      quillOption: quillConfig,
    }
  }
}
</script>

<style>

</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章