富文本框vue 自定义图片上传

31 篇文章 0 订阅
 <ueditor
      ref="by_know"
      :config="{
       initialFrameWidth: null,
       initialFrameHeight: 350,
    }"
      :defaultMsg="form.info"
     :ueditorChange="agreenInfoChange"
></ueditor>
>
agreenInfoChange(msg) {
      this.form.info = msg;//富文本内容
 },
<template>
  <section v-loading="loading" class="ueditor-content">
    <!-- 图片/文件上传 multiple属性多选-->
    <form
      :action="`${$comentUrl}/auth/upload/image`"
      style="display: none"
      id="uploadForm"
      class="uploadForm"
      enctype="multipart/form-data"
      method="post"
    >
      <!-- <input
        type="file"
        name="file"
        id="uploadFile"
        ref="uploadFile"
        @change="uploadFileChange"
      /> -->
      <input
        type="file"
        accept="image"
        name="file"
        @change="uploadFileChange"
        ref="uploadFile"
        id="uploadFile"
      />
    </form>
    <el-dialog
      :append-to-body="true"
      :visible.sync="dialogVisible"
      custom-class="reset-pwd wlm-form-dialog dialog-table"
      width="30%"
    >
      <div v-if="dialogVisible" class="wlm-form">
        <div class="wlm-form-header wlm-dialog-fixheader">
          <span class="wlm-dialog-inlenr">微信图文采集</span>
        </div>
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <div class="wlm-form-content">
            <div class="wlm-dialog-main">
              <div class="wlm-dialog-content flex-col">
                <p>
                  1.下方表单输入链接,可以采集微信内容链接。例如:https://mp.weixin.qq.com/s/MQs5zQcYQlI_RCkf91BgXg
                </p>
                <p style="margin-top: 10px">
                  2.可以使用微信内容复制到编辑器中即可。由于图片采集需要时间。所以等待20秒再提交表单。
                </p>
                <p style="margin-top: 10px">
                  温馨提示:视频,过于复杂的样式,背景图,可能会导致采集失败。
                </p>
                <el-input
                  v-model="materialNewsText"
                  placeholder="采集微信图文内容(填写微信图文链接)"
                  style="margin-top: 10px; width: 90%"
                >
                </el-input>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
        <el-button size="text" type="primary" @click="dialogVisible = false"
          >取消
        </el-button>
        <el-button
          :disabled="dialogLoding"
          :loading="dialogLoding"
          size="small"
          type="primary"
          @click="saveTextarea"
          >采集
        </el-button>
      </footer>
    </el-dialog>
    <vue-ueditor-wrap
      v-if="!destoryed"
      v-show="!destoryed"
      ref="ueditor"
      v-model="msg"
      :config="ueditorConfig"
      :destroy="true"
      :init="ueditorInit"
      @ready="ready"
    ></vue-ueditor-wrap>
    <!-- <p class="orders-gray font-12" style="margin-top:10px;">建议使用图片作为详情内容,从其他编辑器或者平台粘贴可能会出现样式问题,请手动修改。</p>
    <p class="orders-gray font-12">样式有问题的建议先粘贴到word文档(无格式粘贴)再复制到后台</p> -->
  </section>
</template>

<script>
import VueUeditorWrap from "vue-ueditor-wrap";
import $ from "jquery";
import axios from "axios";
import local from "@/utils/local";
export default {
  name: "UE",
  data() {
    return {
      materialNewsText: "",
      dialogVisible: false,
      dialogLoding: false,
      destoryed: false,
      loading: true,
      msg: "",
      isReady: false,
      chooseFilesConfig: {
        type: ["image"],
        model: "normal",
        initList: [],
        file_type: "image",
      },
      chooseFilesVideoConfig: {
        type: ["video"],
        model: "normal",
        initList: [],
        file_type: "video",
      },
      ueditorConfig: {
        UEDITOR_HOME_URL: "UEditor/",
        autoHeightEnabled: false,
        maximumWords: 20000,
        initialFrameHeight: 240,
        initialFrameWidth: "100%",
        enableAutoSave: false,
        toolbars: [
          [
            "source",
            "|",
            "undo",
            "redo",
            "|",
            "bold",
            "italic",
            "underline",
            "strikethrough",
            "removeformat",
            "formatmatch",
            "autotypeset",
            "blockquote",
            "|",
            "forecolor",
            "backcolor",
            "insertorderedlist",
            "insertunorderedlist",
            "horizontal",
            "|",
            "rowspacingtop",
            "rowspacingbottom",
            "lineheight",
            "indent",
            "|",
            "imagenone",
            "imageleft",
            "imageright",
            "imagecenter",
            "|",
            "justifyleft",
            "justifycenter",
            "justifyright",
            "justifyjustify",
            "fullscreen",
            "|",
            "paragraph",
            "fontsize",
            "|",
            "inserttable",
            "deletetable",
            "insertparagraphbeforetable",
            "insertrow",
            "deleterow",
            "insertcol",
            "deletecol",
            "mergecells",
            "mergeright",
            "mergedown",
            "splittocells",
            "splittorows",
            "splittocols",
            "|",
            "link",
          ],
        ],
      },
    };
  },
  computed: {},
  components: {
    VueUeditorWrap
  },
  watch: {
    defaultMsg: {
      handler(newData, oldData) {
        if (typeof newData === "string" && newData !== "") {
          this.msg = newData;
        } else if (newData == "") {
          this.msg = "";
        }
      },
      immediate: true,
      deep: true,
    },
  },
  props: {
    defaultMsg: {
      type: String,
    },
    bindIndex: {
      type: Number,
      required: false,
    },
    ueditorList: {
      type: Array,
      required: false,
    },
    config: {
      type: Object,
    },
    ueditorChange: {
      type: Function,
    },
    defaultFocus: {
      type: Boolean,
    },
    ueditorDisabled: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {},
  methods: {
    saveTextarea() {
      const Base64 = require("js-base64").Base64;
      this.dialogLoding = true;
      getWechatNews({ url: this.materialNewsText }).then((response) => {
        const {
          data: { data: msgData = [] },
        } = response;
        const contentBase = Base64.decode(msgData);
        this.msg = contentBase;
        this.materialNewsText = "";
        this.dialogVisible = false;
        this.dialogLoding = false;
      });
    },
    uploadFileChange(e) {
      console.log(e.target, "图片文件");
      console.log(e.target.files[0], "图片文件");
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
     //关键更改Content-Type为multipart/form-data文件类型
      let instance = axios.create();
      instance.defaults.headers["common"]["X-Requested-With"] =
        "XMLHttpRequest";
      // 设置post请求头
      instance.defaults.headers.post["Content-Type"] =
        "multipart/form-data";
      instance
        .post(`${this.$comentUrl}/auth/upload/image`, formData)
        .then((res) => {
          console.log(res.data.data, "图片路径");
          if (res.data.code == 1) {
            this.$Ueditor.focus();
            this.$Ueditor.execCommand(
              "inserthtml",
              `<img style='font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;' src='${res.data.data}'/>`
            );
          }
        });
    },
    //  `<img style="font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;" src='${res.data.data}'/>`
    // async uploadFileChange(e) {
    //   console.log(e, "文件上传");
    //   let fileInput = document.getElementById("uploadFile");
    //   console.log(fileInput, "fileInput");
    //   let fileName = fileInput.files[0].name;
    //   let ext = fileName.substring(
    //     fileName.lastIndexOf(".") + 1,
    //     fileName.length
    //   );
    //   if (fileInput.files[0].size == 0) {
    //     this.$message.error("不能传空文件");
    //     return;
    //   }
    //   if (!(fileInput.files[0].size / 1024 / 1024 < 10)) {
    //     this.$message({
    //       type: "warning",
    //       message: "上传文件大小不能超过 10MB!",
    //     });
    //     return;
    //   }
    //   // 文件大小转换
    //   // if(fileSize < 1024 ) {
    //   //   sizeNum = fileSize + 'b';
    //   // } else if(fileSize == 1024) {
    //   //   sizeNum = "1KB";
    //   // } else if(fileSize > 1024 && fileSize < (1024 * 1024)) {
    //   //   sizeNum = ((fileSize / 1024).toFixed(1)) + "KB";
    //   // } else if(fileSize == (1024 * 1024)) {
    //   //   sizeNum = "1M";
    //   // } else if(fileSize > (1024 * 1024)) {
    //   //   sizeNum = (fileSize / (1024 * 1024)).toFixed(1) + "M";
    //   // }
    //   // 文件大小转换
    //   let formFile = new FormData();
    //   formFile.append("file", fileInput.files[0]);
    //   console.log(formFile, "formFile");
    //   let type = /png|jpg|bmp|jpeg|gif/i.test(ext) ? "image" : "file";
    //   if (type == "image") {
    //     axios
    //       .post(`${this.$comentUrl}/auth/upload/image`, formFile, {
    //         headers: { "Content-Type": "multipart/form-data" }
    //       })
    //       .then((res) => {
    //         console.log(res, "res");
    //         if (res.code == 1) {
    //           console.log(res, "res");
    //           this.$Ueditor.focus();
    //           this.$Ueditor.execCommand(
    //             "inserthtml",
    //             `<img style="font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;" src="${res.data}"/>`
    //           );
    //         }
    //       });
    //   } else if (type == "file") {
    //     axios
    //       .post(`${this.$comentUrl}/auth/upload/image`, formFile, {
    //         headers: { "Content-Type": "multipart/form-data" }})
    //       .then((res) => {
    //         console.log(res, "res");
    //         if (res.code == 1) {
    //           this.$Ueditor.focus();
    //           this.$Ueditor.execCommand(
    //             "inserthtml",
    //             `<img style="font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;" src="${res.data}"/>`
    //           );
    //         }
    //       });
    //   }
    // },

    uploadSaveChange(fileList) {
      // this.$Ueditor.focus();
      if (fileList.length > 0) {
        fileList.map((item) => {
          if (item.file_type !== "video") {
            this.$Ueditor.execCommand(
              "inserthtml",
              `<img style="font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;" src="${item["file_path"]}"/>`
            );
          } else {
            this.$Ueditor.execCommand("insertvideo", {
              url: item["file_path"],
              width: 300,
              height: 200,
            });
          }
        });
      }
    },
    ueditorInit(...arg) {
      const UE = window.UE;
      const that = this;
      // 自定义上传图片和视频按钮
      UE.registerUI("buttonimg", function (editor, uiName) {
        // 注册按钮执行时的command命令,使用命令默认就会带有回退操作
        // editor.registerCommand(uiName, {
        //   execCommand: function() {
        //     alert('execCommand:' + uiName)
        //   }
        // })
        // 创建一个button
        var btn = new UE.ui.Button({
          // 按钮的名字
          name: "uiName",
          // 提示
          title: "上传图片",
          // 添加额外样式,指定icon图标,这里默认使用一个重复的icon
          cssRules: "background-position: -726px -77px;",
          // 点击时执行的命令
          onclick: function () {
            // 这里可以不用执行命令,做你自己的操作也可
            editor.execCommand(uiName);
            // 执行自定义上传
            that.$Ueditor.focus();
            console.log("点击了");
            $("#uploadFile").trigger("click");
          },
        });
        // 当点到编辑内容上时,按钮要做的状态反射
        editor.addListener("selectionchange", function () {
          var state = editor.queryCommandState(uiName);
          if (state === -1) {
            btn.setDisabled(true);
            btn.setChecked(false);
          } else {
            btn.setDisabled(false);
            btn.setChecked(state);
          }
        });
        // 返回button
        return btn;
      });
    },
    ready(editorInstance) {
      this.loading = false;
      this.$Ueditor = editorInstance;
      this.$UeditorKey = editorInstance.key;
      if (this.ueditorDisabled) {
        this.$Ueditor.setDisabled();
      }
      if (
        Object.prototype.toString.call(this.ueditorChange) ===
        "[object Function]"
      ) {
        this.$Ueditor.addListener("contentChange", (res) => {
          const content = this.getUEContent("getContent");
          this.ueditorChange(content, this.isReady);
          this.isReady = true;
        });
        this.$Ueditor.addListener("afterSelectionChange", () => {
          const content = this.getUEContent("getContent");
          this.ueditorChange(content);
        });
      }
    },
    setDisabled() {
      if (this.$Ueditor) {
        this.$Ueditor.setDisabled();
      }
    },
    getUEContent(getType = "getPlainTxt") {
      // 获取内容方法
      return this.$Ueditor[getType]();
    },
  },
  beforeDestroy() {
    this.destoryed = true;
  },
  destoryed() {
    this.$Ueditor.destory();
  },
};
</script>

<style lang="less" scoped>
.ueditor-content {
  width: 700px;
  position: relative;
  z-index: 0;
}

.imoprt-uedotor {
  position: absolute;
  padding: 5px;
  font-size: 12px;
  top: 34px;
  right: 4px;
  z-index: 2000;
}

/deep/ .edui-editor div {
  line-height: 20px;
  padding-bottom: 2px;
}

/deep/ .edui-default .edui-editor-toolbarboxouter {
  border-bottom: none !important;
  background-image: none !important;
}

/deep/ .edui-default .edui-editor-breadcrumb {
  margin: 5px 0 0 6px !important;
}

/deep/ .edui-default .edui-editor-toolbarbox {
  border-bottom: 0;
  box-shadow: none;
  background-color: #fafafa;
  z-index: 2000;
}

/deep/ .edui-default iframe body {
  overflow-x: hidden;
}

/deep/ textarea[name="editorValue"] {
  display: none !important;
}
</style>

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在tinymce/tinymce-vue富文本编辑器中实现图片上传功能,你可以按照以下步骤操作: 1. 首先,确保你已经安装了tinymce和tinymce-vue的依赖包。你可以去[TinyMCE官方网站](https://www.tiny.cloud/get-tiny/self-hosted/)下载最新的TinyMCE压缩包,并解压到你的项目目录中。然后,安装tinymce-vue依赖包,可以使用npm或yarn进行安装。 2. 接下来,将TinyMCE的skins文件夹复制到你的项目的public文件夹下。这个文件夹包含了富文本编辑器的样式文件。 3. 然后,创建一个Vue组件来封装el-upload控件,并将其整合到tinymce-vue中。你可以将这个组件放在你的项目的src/components文件夹下。具体的组件代码可以参考上述提供的链接。 通过以上步骤,你就可以在tinymce/tinymce-vue富文本编辑器中实现图片上传功能了。请注意,这只是一种实现方式,具体的实现方式可能因项目需求的不同而有所差异。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [vue3 中 tinymce+tinymce-vue 富文本编辑器使用](https://blog.csdn.net/oooosadas/article/details/131176384)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [vue-tinymce 富文本编辑器自定义图片上传](https://download.csdn.net/download/hadues/13183093)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值