vue-quill-editor添加图片上传自定义压缩或修改为上传到服务器返回url地址

89 篇文章 7 订阅
35 篇文章 1 订阅

1、图片压缩方式:
代码:

<template>
  <v-container fluid class="white">
    <v-form ref="form">
      <v-text-field
        v-model="title"
        :error-messages="titleErrors"
        :counter="20"
        label="标题"
        required
        @input="$v.title.$touch()"
        @blur="$v.title.$touch()"
      ></v-text-field>
      <v-text-field v-model="brief" label="简介"></v-text-field>
      <v-file-input
        accept="image/jpeg, image/png"
        label="封面图片"
        prepend-icon="mdi-file-image-outline"
        @change="handleInputChange"
      ></v-file-input>
      <v-row>
        <v-col cols="12">
          <quill-editor
            ref="myQuillEditor"
            v-model="content"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          >
          </quill-editor>
        </v-col>
      </v-row>
      <v-btn class="mr-4" outlined @click="submit">提交</v-btn>
      <v-btn outlined @click="clear">清空</v-btn>
    </v-form>
  </v-container>
</template>

<script>
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"],
  ["blockquote", "code-block"],
  [{ header: 1 }, { header: 2 }],
  [{ list: "ordered" }, { list: "bullet" }],
  [{ indent: "-1" }, { indent: "+1" }],
  [{ color: [] }, { background: [] }],
  ["image"]
];
const handlers = {
  image: function image() {
    let self = this;
    var fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      // 可设置上传图片的格式
      fileInput.setAttribute("accept", "image/png, image/gif, image/jpeg");
      fileInput.classList.add("ql-image");
      // 监听选择文件
      fileInput.addEventListener("change", function() {
        console.log(fileInput.files[0]);
        let file = fileInput.files[0];
        if (!/image\/\w+/.test(file.type)) {
          console.log("图片格式不正确");
          return false;
        }
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function() {
          let img = new Image();
          img.src = this.result;
          img.onload = function() {
            let that = this;
            let scale = 800 / that.width;
            let w = 800;
            let h = that.height * scale;
            // let w = that.width;
            // let h = that.height;
            let canvas = document.createElement("canvas");
            let ctx = canvas.getContext("2d");
            let anw = document.createAttribute("width");
            anw.nodeValue = w;
            let anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            let base64 = canvas.toDataURL("image/jpeg", 0.5);
            console.log(base64);
            let length = self.quill.getSelection(true).index;
            self.quill.insertEmbed(length, "image", base64);
            self.quill.setSelection(length + 1);
          };
        };
        // 创建formData
        // var formData = new FormData();
        // formData.append(uploadConfig.name, fileInput.files[0]);
        // formData.append("object", "product");
        // 图片上传
        // 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();
  },
  dealImage: function(path, obj, callback) {
    var img = new Image();
    img.src = path;
    img.onload = function() {
      var that = this;
      // 默认按比例压缩
      var w = that.width,
        h = that.height,
        scale = w / h;
      w = obj.width || w;
      h = obj.height || w / scale;
      var quality = obj.quality || 0.7; // 默认图片质量为0.7
      //生成canvas
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      // 图像质量
      if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
        quality = obj.quality;
      }
      // quality值越小,所绘制出的图像越模糊
      var base64 = canvas.toDataURL("image/jpeg", quality);
      // 回调函数返回base64的值
      callback(base64);
    };
  }
};
import { validationMixin } from "vuelidate";
import { required } from "vuelidate/lib/validators";
import { articleAdd, upload } from "@/api/blog";
export default {
  mixins: [validationMixin],
  validations: {
    title: { required }
  },
  name: "ArticleEdit",
  components: {},
  data() {
    return {
      title: "",
      brief: "",
      content: "",
      cover_img: "",
      editorOption: {
        // 编辑器自定义
        placeholder: "请输入内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: handlers
          }
        }
      }
    };
  },
  computed: {
    titleErrors() {
      const errors = [];
      if (!this.$v.title.$dirty) return errors;
      !this.$v.title.required && errors.push("Title is required.");
      return errors;
    }
  },
  methods: {
    submit() {
      this.$v.$touch();
      let para = {
        title: this.title,
        brief: this.brief,
        cover_img: this.cover_img,
        content: this.content
      };
      articleAdd(para)
        .then(() => {
          this.$router.push({
            name: "Home",
            params: {
              reload: true
            }
          });
          this.clear();
        })
        .catch(err => {
          console.log(err);
        });
    },
    clear() {
      this.$v.$reset();
      this.$refs.form.reset();
      this.title = "";
      this.brief = "";
      this.cover_img = "";
      this.content = "";
    },
    handleInputChange(v) {
      if (v) {
        let data = new FormData();
        data.append("fileName", v.name);
        data.append("file", v);
        upload(data)
          .then(res => {
            this.cover_img = res.data;
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    // 失去焦点事件
    onEditorBlur() {},
    // 获得焦点事件
    onEditorFocus() {},
    // 内容改变事件
    onEditorChange() {}
  }
};
</script>

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现vue-quill-editor配合elementui上传组件自定义图片上传操作,可以使用以下步骤: 1. 在vue-quill-editor中配置图片上传的方法: ``` <template> <quill-editor v-model="content" ref="myQuillEditor" :options="editorOption"></quill-editor> </template> <script> import { quillEditor } from 'vue-quill-editor' export default { components: { quillEditor }, data() { return { content: '', editorOption: { modules: { toolbar: [ ['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'], ['image'] ], imageUploader: { upload: file => { // 自定义图片上传 } } }, placeholder: '请输入内容', theme: 'snow' } } } } </script> ``` 在`modules`中添加`imageUploader`属性,用于自定义图片上传操作,其中`upload`方法就是自定义图片上传方法。 2. 在自定义图片上传方法中,使用elementui的上传组件进行图片上传: ``` <template> <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false" :on-success="handleSuccess"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </template> <script> export default { data() { return { imageUrl: '', uploadUrl: '/api/upload' } }, methods: { handleSuccess(response) { // 上传成功后,获取图片地址,然后插入到编辑器中 const url = response.url const quillEditor = this.$refs.myQuillEditor.quill const range = quillEditor.getSelection(true) const index = range.index + range.length quillEditor.insertEmbed(index, 'image', url) } } } </script> ``` 3. 在handleSuccess方法中,获取上传成功后的图片地址,然后通过`quillEditor.insertEmbed`方法将图片插入到编辑器中。 这样,就可以实现vue-quill-editor配合elementui上传组件自定义图片上传操作了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值