• quill富文本框图片上传重写


    1、在 vue 页面中

    <quill-editor ref="myTextEditor" v-model="content"
     :options="quillOption"></quill-editor>
     
    <script>
    import { quillEditor } from "vue-quill-editor";
    import quillConfig from "@/assets/js/quill-config.js";
    data(){
        return{
            quillOption: quillConfig,
            content
        }
    },
    components:{
        quillEditor
    }
    </script>

    2、在 assets/js 中新建文件 quill-config.js

    import hljs from 'highlight.js'; // 代码高亮
    
    /*富文本编辑图片上传配置*/
    const uploadConfig = {
      action: 'http://127.0.0.1:3000/background/imgs', // 必填参数 图片上传地址
      methods: 'POST', // 必填参数 图片上传方式
      token: sessionStorage.getItem('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 // 事件重写
        },
       syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value; // 这里就是代码高亮需要配置的地方
           }
         }
       }
    };

    3、nodejs 后台解析

    router.post('/insert', (req, res) => {
      var a_title = req.body.a_title
      var a_date = req.body.a_date
      var a_content = req.body.a_content
    
      var belong = req.body.belong
      var a_author = req.body.a_author
      var a_tags = req.body.a_tags
      var a_abstract = req.body.a_abstract
      var a_state = req.body.a_state
      var u_id = req.body.u_id
      var imgReg = /|/>)/gi;
      //匹配src属性
      var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
      var arr = a_content.match(imgReg);
      // console.log('图片', arr)
      if (arr != null) {
        console.log('所有图片', arr)
        // alert("所有已成功匹配图片的数组:" + arr);
        var srcArr = [] // 图片地址
        for (var i = 0; i < arr.length; i++) {
          var src = arr[i].match(srcReg);
          srcArr.push(src[1])
        }
        console.log('图片地址', srcArr)
        a_img = JSON.stringify(srcArr)
    
      }
      var sql = `insert into article(a_title,a_date,a_content,a_img,a_author,a_tags,a_abstract,a_state,u_id,belong)
      value(?,?,?,?,?,?,?,?,?,?)
      `
      db.connect(sql, [a_title, a_date, a_content, srcArr, a_author, a_tags, a_abstract, a_state, u_id, belong], (err, data) => {
        console.log('错误', err)
        if (err) return res.json({
          code: 0,
          msg: '错误'
        })
        res.json({
          code: 200,
          msg: '发布文章成功'
        })
      })
    })
  • 相关阅读:
    Finance_Time-Series-Analysis-with-app-in-R
    Linear_algebra_06_二次型
    Linear_algebra_05_相似对角形
    病理学
    S&p_14_参数的假设检验
    S&p_13_参数区间估计
    Finance_Analysis-of-Financial-Time-Series
    817. Linked List Components
    811. Subdomain Visit Count
    807. Max Increase to Keep City Skyline
  • 原文地址:https://www.cnblogs.com/lin961234478/p/13602629.html
Copyright © 2020-2023  润新知