Vue uses vue-quill-editor to upload the image path as the server path

Foreword :
The vue-quill-editor rich text box plug-in is widely used. Recently, the company needs to write a guidance document, but it is found that when uploading a picture, it directly converts the picture to base64 for display, and the content of the text editor submitted at this time must also be A large string of html+image base64 strings, which of course cannot be directly stored in the database database, unless you are not afraid of a violent beating from the back end
insert image description here

Solution :
vue-quill-editor has a lot of open extension and custom methods. We get the image in our own toolbar during the mounted initialization, hijack the image handler method, and call a hidden input:file on our page upload files. Use the change method of input to call the interface, get the returned url, and go directly to the next step.

1. Download the vue-quill-editor plugin

npm install vue-quill-editor --save

Since vue-quill-editor needs to depend on quill, those without quill should also be downloaded

npm install quill --save

2. Import in the page

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import {
    
     quillEditor } from 'vue-quill-editor'

export default {
    
    
  components: {
    
    
    quillEditor
  }
}

3. Use in the page

<template>
  <div id="app">
    <quill-editor :options="editorOption" v-model="content" ref="myQuillEditor">
    </quill-editor>
    <input
      type="file"
      hidden
      accept=".jpg,.png"
      ref="fileBtn"
      @change="handleChange"
    />
    <button @click="submit">提交</button>
  </div>
</template>

<script>
import http from "./script/httpRequest.js";
import axios from "axios";
import {
     
      quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

export default {
     
     
  data() {
     
     
    return {
     
     
      content: "",
      editorOption: {
     
     
        placeholder: "请输入信息详情",
      },
    };
  },
  components: {
     
     
    quillEditor,
  },
  mounted() {
     
     
    if (this.$refs.myQuillEditor) {
     
     
      //myQuillEditor改成自己的
      this.$refs.myQuillEditor.quill
        .getModule("toolbar")
        .addHandler("image", this.imgHandler);
      //这里初始化,劫持toolbar的image的handler方法,在mounted中处理
    }
  },
  methods: {
     
     
    submit() {
     
     
      console.log(this.content);
    },
    imgHandler(state) {
     
     
      if (state) {
     
     
        //触发input的单击 ,fileBtn换成自己的
        this.$refs.fileBtn.click();
      }
    },
    handleChange(e) {
     
     
      const files = Array.prototype.slice.call(e.target.files);
      if (!files) {
     
     
        return;
      }
      let form = new FormData();
      form.append("file", files[0]);
      //由于我的接口是base64上传到服务器的,需要转成base64,否则直接将form文件上传即可
      let reader = new FileReader();
      reader.readAsDataURL(files[0]);
      reader.onload = (e) => {
     
     
        //将url改成自己的地址
        axios.post(url, {
     
     
            image: e.target.result, //如果是是以文件流上传,则改成form
          })
          .then((res) => {
     
     
            console.log(res);
            //这里设置为空是为了联系上传同张图可以触发change事件
            this.$refs.fileBtn.value = "";
            if (res.status === 200) {
     
     
              let selection = this.$refs.myQuillEditor.quill.getSelection();
              //这里就是返回的图片地址,如果接口返回的不是可以访问的地址,要自己拼接
              let imgUrl = res.data.imgUrl;
              //获取quill的光标,插入图片
              this.$refs.myQuillEditor.quill.insertEmbed(
                selection != null ? selection.index : 0,
                "image",
                imgUrl
              );
              //插入完成后,光标往后移动一位
              this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
            }
          });
      };
    },
  },
};
</script>

4. Cross-domain problems
If cross-domain is not configured, the page will report cross-domain errors, which is easy to understand. After all, the domain name on the server side is inconsistent with the domain name port running by itself, then you need to configure it at this time
. 1. Now the new version The vue scaffolding has no vue.config.js file. If there is one, configure it directly under this file. If not, add a vue.config.js file in the same directory as package.json.

module.exports = {
    
    
    devServer: {
    
    
        open: true, //是否自动弹出浏览器页面
        host: "localhost", 
        port: '8084', 
        proxy: {
    
    
            '/api': {
    
    
                target: 'http://localhost:7001', //API服务器的地址
                changeOrigin: true,
            }
        },
        headers: {
    
    
            'Access-Control-Allow-Origin': '*',
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_42000816/article/details/111307756