vue下的富文本編輯器quill-editor和go的後端搭配圖片上傳

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

     創建一個quill-config文件

/*富文本編輯圖片上傳配置*/

複製代碼
/*富文本編輯圖片上傳配置*/
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>
複製代碼

 

2、 修改編輯器的工具欄

 

複製代碼
<quill-editor
          style="height:100px"
          v-model="contentFY"
          ref="myQuillEditorFY"
          :options="editorOptionFY"
          @blur="onEditorBlurFY($event)" @focus="onEditorFocusFY($event)"
          @change="onEditorChangeFY($event)">
        </quill-editor>
複製代碼

 

複製代碼
 editorOption: {
          modules:{
            toolbar:[
              ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
              ['blockquote', 'code-block']
            ]
          },
          placeholder: '請輸入內容及工作量',
        },
複製代碼

 

那麼toolbar工具欄對應功能的模塊名是什麼呢 我繼續往下看文檔 發現大致上有以下的功能

背景顏色 - background
加粗- bold
顏色 - color
字體 - font
內聯代碼 - code
斜體 - italic
鏈接 - link
大小 - size
刪除線 - strike
上標/下標 - script
下劃線 - underline
引用- blockquote
標題 - header
縮進 - indent
列表 - list
文本對齊 - align
文本方向 - direction
代碼塊 - code-block
公式 - formula
圖片 - image
視頻 - video
清除字體樣式- clean

 

 

go採用的是 goframe

package write

import (
   "github.com/gogf/gf/frame/g"
   "github.com/gogf/gf/net/ghttp"
   "github.com/gogf/gf/os/gtime"
   "github.com/gohouse/random"
   "log"
   "strings"
)

var UploadService = UploadFunc{}

type UploadFunc struct{}

func (u *UploadFunc) File(r *ghttp.Request) {
   file := r.GetUploadFile("img")
   log.Println(file)
   s := file.Filename
   sep := "."
   ext := strings.Split(s, sep)
   file.Filename = ""

   file.Filename += string(gtime.Now().Format("Y-m-d+H-i-s"))
   file.Filename += "!!"

   file.Filename +=random.Random(12) + "." + ext[1]
   _path := g.Cfg().Get("server.Path")
   fullPath := g.Cfg().Get("server.ImgDomain")
   fileName, err := file.Save(_path.(string) + "/")
   if err != nil {
      r.Response.Write(err)
      return
   }
   fullName := fullPath.(string) + "/" + fileName

   res := g.Map{
      "status": "success",
      "path":   fullName,
   }

   r.Response.WriteJson(res)

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