Vue中使用wangEditor富文本编辑器|图片上传(含后端代码)

一、效果

二、安装依赖

npm install wangeditor --save
npm install @wangeditor/editor-for-vue@next --save

三、使用

在src下common文件夹下创建wangEditor文件夹,并在其文件夹下创建index.vue文件

<template>
  <div style="border: 1px solid #ccc; width: 100%">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
export default {
  components: {
    Editor,
    Toolbar,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  watch: {
    value(val) {
      setTimeout(() => {
        this.html = val;
      }, 1000);
    },
  },

  data() {
    return {
      editor: null,
      html: "",
      mode: "default",
      editorConfig: {
        placeholder: "请输入产品信息...",
        backColor: "red", // 背景颜色
        MENU_CONF: {
          uploadImage: {
            customUpload: this.uploaadImg,
          },
          uploadVideo: {
            customUpload: this.uploaadVideo,
          },
        },
      },
      toolbarConfig: {},
    };
  },
  methods: {
    handleCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ,否则会报错
      //   设置工具栏详情
      this.toolbarConfig = {
        excludeKeys: [
          "insertVideo",
          "uploadVideo",
          "group-video",
          "fullScreen",
        ],
      };
    },
    handleChange(content) {
      const toolbar = DomEditor.getToolbar(content);
      //   查看工具栏列表toolbar.getConfig().toolbarKeys
      this.$emit("change", this.html);
    },
    uploaadImg(file, insertFn) {
      this.$emit("uploadImg", file, insertFn);
    },
    uploaadVideo(file, insertFn) {
      this.$emit("uploadVideo", file, insertFn);
    },
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 销毁编辑器
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

在需要使用wangEditor的组件中编写如下信息:

<template>
     <WangEditor
       v-model="ruleForm.reproduceStep"
       @change="richTextChangeData"
       @uploadImg="richTextUploadImg"
     ></WangEditor>
</template>


<script>
import {
  uploadImg,
} from "@/apis/uploadImg";
import wangEditor from "@/components/wangEditor";

export default {
  name: "product",
  components: { wangEditor },
  data() {
    return {
      ruleForm: {
        reproduceStep: "",
      },
    };
  },

  methods: {
    richTextChangeData(val) {
      // 获取最新的html数据
      this.form.productIntroduction = val;
    },
    setFormData() {
      this.ruleForm.reproduceStep = "<h1>h1</h1>";
    },

    async richTextUploadImg(file, insertFn) {
      // 处理入参
      const formData = new FormData();
      formData.append("file", file);
      await uploadImg(formData).then((res) => {
        insertFn(res.data.data.imgUrl); // 页面插入图片
      });
    },
  },
};
</script>

创建文件上传API

  • uploadImg.js文件
// 图片上传
export const uploadImg = (formData) => {
  return request.post("/upload/img", formData, {
    headers: {
      "Content-Type": "multipart/form-data"
    },
  });
};

需要自己编写后端代码,参考:

  • 控制层:
//    上传图片
    @PostMapping("/uploadimg")
    public Result uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//获取图片原始文件名
        int index = originalFilename.lastIndexOf(".");
        String extention = originalFilename.substring(index);//获得图片后缀名  .jpg
        String fileName =  UUID.randomUUID().toString() + extention; //进行拼接
        fileName = fileName.replace("-",""); //将文件路径中的-替换掉
        String uploadQiniu = QiniuUtils.uploadQiniu(file.getBytes(), fileName, "imgUpload/");
        return Result.success("上传图片成功",uploadQiniu);
    }

七牛云存储方法

  • QiniuUtils.java
package xxx.xxx.xxx.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiniuUtils {

    //访问授权码
    public  static String accessKey = "";
    //秘密钥匙
    public  static String secretKey = "";
    //空间名称
    public  static String bucket = "";
    //外链域名
    public static String domain = "";


    //上传方式二:文件上传 通过上传文件的方式上传到存储空间
    public static String uploadQiniu(byte[] bytes, String fileName,String path){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = path + fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            //返回文件完整路径
            return domain+"/"+putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
                return "";
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return "";
    }


    //删除文件 参数:存储的图片文件名
    public static void deleteFileFromQiniu(String fileName,String path){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        String key = path + fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常,说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}

 

为了在Vue3使用wangEditor富文本批量上传图片,你需要按照以下步骤进行操作: 1.首先,你需要安装wangEditor。你可以通过npm安装wangEditor,命令如下: ```shell npm install wangeditor --save ``` 2.在你的Vue组件引入wangEditor,并在mounted钩子函数初始化wangEditor。你需要在初始化时设置上传图片的配置,包括上传图片的路径和上传图片的处理函数。以下是一个示例: ```javascript <template> <div ref="editorElem" /> </template> <script> import wangEditor from 'wangeditor' export default { mounted() { const editor = new wangEditor(this.$refs.editorElem) // 配置上传图片的路径和处理函数 editor.customConfig.uploadImgServer = '/upload' editor.customConfig.uploadImgHooks = { before: function(xhr, editor, files) { // 在这里可以对上传的图片进行处理 }, success: function(xhr, editor, result) { // 图片上传成功后的处理函数 }, fail: function(xhr, editor, result) { // 图片上传失败后的处理函数 }, error: function(xhr, editor) { // 图片上传出错的处理函数 }, timeout: function(xhr, editor) { // 图片上传超时的处理函数 }, customInsert: function(insertImg, result, editor) { // 在这里可以对插入的图片进行处理 insertImg(result.data) } } editor.create() } } </script> ``` 在上面的代码,你需要将`/upload`替换为你的图片上传路径。在`uploadImgHooks`,你可以设置上传图片的处理函数,包括上传前的处理函数、上传成功后的处理函数、上传失败后的处理函数、上传出错的处理函数、上传超时的处理函数和插入图片后的处理函数。在`customInsert`函数,你可以对插入的图片进行处理。 3.在你的服务器端设置图片上传的处理函数。在上传图片的处理函数,你需要将上传的图片保存到服务器上,并返回一个JSON格式的数据,包括图片的URL和图片的宽度和高度。以下是一个示例: ```python import os from flask import Flask, request, jsonify from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) url = 'http://example.com/uploads/' + filename return jsonify({ 'errno': 0, 'data': [url], }) ``` 在上面的代码,你需要将`http://example.com/uploads/`替换为你的图片上传路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值