wangEditor+vue上传图片到七牛云配置

1.下载七牛云

// 下载qiniu-js
npm install qiniu-js
// 在页面中引入
import * as qiniu from 'qiniu-js'

2.首先创建一个MyWangEditor的组件

<template lang="html">
  <div class="editor">
    <div ref="toolbar" class="toolbar"></div>
    <div ref="editor" class="text" :style="{ minHeight: h, width: w }"></div>
  </div>
</template>

<script>
import E from "wangeditor";
import { GetqiniuToken } from "@/api/article";//获取七牛云token接口
import * as qiniu from "qiniu-js";
let imgUrl = "";

export default {
  name: "editor",
  props: {
    w: {
      type: String,
      default: "100%",
    },
    h: {
      type: String,
      default: "600px",
    },
    value: {
      type: String,
      default: "",
    },
    isClear: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      QiniuData: { token: "" },
      getToken: "",
      action: imgUrl + "接口地址",
      editor: null,
      info_: null,
      menus: [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "italic", // 斜体
        "indent", //缩进
        "lineHeight", //行高
        "underline", // 下划线
        "strikeThrough", // 删除线
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        "link", // 插入链接
        "list", // 列表
        "justify", // 对齐方式
        "quote", // 引用
        "emoticon", // 表情
        "image", // 插入图片
        "table", // 表格
        // "todo", //待办事项
        // "code", // 插入代码
        // "video",
        "undo", // 撤销
        "redo", // 重复
        "splitLine", //分割线
        "fullscreen", // 全屏
        "tableHeader", // 表头
        "tableFullWidth", // 宽度自适应
      ],
      colors: [
        "#000000",
        "#ffffff",
        "#eeece0",
        "#1c487f",
        "#4d80bf",
        "#c24f4a",
        "#8baa4a",
        "#7b5ba1",
        "#46acc8",
        "#f9963b",
        "#FF0000",
        "#00FF00",
        "#0000FF",
        "#FF00FF",
        "#00FFFF",
        "#FFFF00",
        "#000000",
        "#70DB93",
        "#5C3317",
        "#9F5F9F",
        "#B5A642",
        "#D9D919",
        "#A67D3D",
        "#8C7853",
        "#A67D3D",
        "#5F9F9F",
        "#D98719",
        "#B87333",
      ],
    };
  },
  model: {
    prop: "value",
    event: "change",
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear();
        this.info_ = null;
      }
    },
    value: function (value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value);
      }
    },
    //value为编辑框输入的内容,这里我监听了一下值,当父组件调用得时候,如果给value赋值了,子组件将会显示父组件赋给的值
  },
  computed: {},
  created() {},
  mounted() {
    GetqiniuToken().then((res) => {
      console.log("提交", res);
      this.getToken = res.token;
    });
    this.seteditor();
    this.editor.txt.html(this.value);
  },
  methods: {
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    // console.log(sayHello());
    // 打印的是promise对象:Promise{<fulfilled>: 'hello world'}
    // 因为是个promise对象,则需要使用.then获取promise的返回值
    // 以上打印的顺序:先打印 123   再打印 'hello world'
    //   },
    seteditor() {
      this.editor = new E(this.$refs.toolbar, this.$refs.editor);
      this.editor.customConfig = this.editor.customConfig
        ? this.editor.customConfig
        : this.editor.config;
      this.editor.customConfig.menus = this.menus;
      // 上传图片
      this.editor.customConfig.uploadImgShowBase64 = false; //如果为true,则不用配置下面的
      this.editor.customConfig.pasteIgnoreImg = false; //忽略粘贴的图片
      this.editor.customConfig.pasteFilterStyle = false; //关闭样式过滤
      // 配置行高
      this.editor.customConfig.lineHeights = [
        "1",
        "1.15",
        "1.6",
        "2",
        "2.5",
        "3",
      ];
      // 配置颜色(文字颜色、背景色)
      this.editor.customConfig.colors = this.colors;
      console.log("请求", this.editor.customConfig);
      this.editor.customConfig.uploadImgHeaders = {
        Authorization: this.getToken,
      }; // 设置请求头
      // 上传图片
      // 上传到七牛云
      let that = this;
      this.editor.customConfig.customUploadImg = function (
        resultFiles,
        insertImgFn
      ) {
        console.log("resultFiles", resultFiles);
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后,插入到编辑器的方法
        //有可能会上传多张图片,上传多张图片就需要进行遍历
        resultFiles.map((item) => {
          console.log("上传图片", item, insertImgFn);
          // _this.getUploadImg(item, insertImgFn);
          that.getUploadFile(item, insertImgFn);
        });
      };
      //可使用监听函数在上传图片的不同阶段做相应处理
      this.editor.customConfig.uploadImgHooks = {
        //服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错
        customInsert: function (insertImg, result, editor) {
          if (result.code == 200) {
            console.log("图片上传了嘛", insertImg, result, editor);
            const link = result.data;
            // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
            // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
            // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
            insertImg(link); // result 必须是一个 JSON 格式字符串!!!否则报错
          } else {
            this.$message({
              message: result.message,
              type: "warning",
            });
          }
        },
      };
      // 配置菜单
      //连接
      (this.editor.customConfig.linkCheck = function (text, link) {
        console.log("插入的文字", text); // 插入的文字
        console.log("插入的链接", link); // 插入的链接
        return true; // 返回 true 表示校验成功
        // return '验证失败' // 返回字符串,即校验失败的提示信息
      }),
        (this.editor.customConfig.onchange = (html) => {
          this.info_ = html; // 绑定当前逐渐地值
          this.$emit("change", this.info_); // 将内容同步到父组件中
        });
      // 创建富文本编辑器
      this.editor.create();
    },
    // 上传图片/视频到七牛云
    getUploadFile(file, Rendering) {
      // 获取七牛云的token
      GetqiniuToken().then((res) => {
        this.QiniuData.token = res.token;
        //配置信息
        var config = {
          useCdnDomain: true, //表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false
        };
        //额外的信息
        var putExtra = {
          // fname: "", //文件原文件名
          // params: {}, //object,用来放置自定义变量
          // mimeType: null, // null || array,用来限定上传文件类型,指定null时自动判断文件类型
        };
        let suffix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取后缀
        // 设置唯一的文件名
        const key =
          "cwfile/" + new Date().getTime() + "_" + file.size + file.name;
        /**
         * file: Blob 对象,上传的文件
         * key: 文件资源名
         * token: 上传验证信息,前端通过接口请求后端获得
         * config: object
         * putExtra
         */
        // file:图片数据;key:图片名称;token:服务端获取的token;putExtra:额外的参数;config:其他配置
        const observable = qiniu.upload(
          file,
          key,
          this.QiniuData.token,
          putExtra,
          config
        );
        // 文件上传
        var observer = {
          //  正在上传 接收上传进度信息
          next(res) {
            // 上传进度  parseInt(res.total.percent)
            console.log("next-res", res, parseInt(res.total.percent));
            // if(parseInt(res.total.percent)==100){
            //     console.log("success")
            // }
          },
          // 接收上传错误信息
          error(err) {
            console.log(err);
            this.$message.error("文件上传失败");
          },

          // 接收上传完成后的信息
          complete(res) {
            console.log("complete-res", res);
            Rendering("https://cyvideo.i-oranges.com/" + res.key);
          },
        };
        var subscription = observable.subscribe(observer); // 上传开始
      });
    },
  },
};
</script>

<style lang="css">
.videoWarp {
  display: flex;
  justify-content: flex-end;
}
.warp {
  display: inline-block;
  position: relative;
  top: 42px;
  /* left: 98px; */
  z-index: 100000;
  width: 67px;
  height: 36px;
  border: 1px border #dee5ed;
  /*  background-color: #409EFF; */
  /* color: white; */
  font-weight: bold;
  border-radius: 10px 10px;
}

.editor {
  width: 90%;
  /* margin: 0 auto; */
  position: relative;
  z-index: 0;
}

.toolbar {
  border: 1px solid #ccc;
}

.text {
  border: 1px solid #ccc;
  min-height: 500px;
}
</style>

3.页面引入组件

  <my-wangeditor
                  v-model="form.activityImg"
                  :isClear="isClear"
                  @change="changeImg"
                ></my-wangeditor>
   


import myWangeditor from "@/components/MyWangEditor.vue";
export default {
  components: { myWangeditor },
   data() {
    return {
    form:{
    activityImg :' '
    }
    }
    },
   methods: {
    changeImg(e) {
      console.log("上传", e);
      this.form.activityImg = e;
    },
   }
  }
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 首先,需要在七牛云上创建一个存储空间,并获取该存储空间的accessKey、secretKey、bucket和domain。 2. 在Springboot中引入七牛云的Java SDK,可以通过Maven或Gradle进行引入。例如,在Maven中添加以下依赖: ``` <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.2.0, 7.2.99]</version> </dependency> ``` 3. 创建一个七牛云配置类,用于存储accessKey、secretKey、bucket和domain等配置信息。 ``` @Configuration public class QiniuConfig { @Value("${qiniu.accessKey}") private String accessKey; @Value("${qiniu.secretKey}") private String secretKey; @Value("${qiniu.bucket}") private String bucket; @Value("${qiniu.domain}") private String domain; @Bean public Auth auth() { return Auth.create(accessKey, secretKey); } @Bean public Configuration configuration() { return new Configuration(Zone.zone0()); } @Bean public UploadManager uploadManager() { return new UploadManager(configuration()); } @Bean public BucketManager bucketManager() { return new BucketManager(auth(), configuration()); } @Bean public StringMap putPolicy() { StringMap putPolicy = new StringMap(); putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"name\":\"$(fname)\",\"size\":$(fsize)}"); return putPolicy; } @Bean public String uploadToken() { return auth().uploadToken(bucket, null, 3600, putPolicy()); } @Bean public String domain() { return domain; } } ``` 4. 在Vue中使用element-ui的上传组件,设置上传的接口为Springboot的接口。 ``` <el-upload class="upload-demo" action="/api/upload" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload" :headers="{Authorization: 'Bearer ' + token}" > <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> ``` 5. 在Springboot中编写上传接口,在该接口中使用七牛云的Java SDK进行上传。 ``` @RestController @RequestMapping("/api") public class UploadController { @Autowired private UploadManager uploadManager; @Autowired private String uploadToken; @Autowired private String domain; @PostMapping("/upload") public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) throws IOException { try { Response response = uploadManager.put(file.getBytes(), null, uploadToken); if (response.isOK()) { String key = JSON.parseObject(response.bodyString()).getString("key"); return ResponseEntity.ok(domain + "/" + key); } } catch (QiniuException e) { e.printStackTrace(); } return ResponseEntity.badRequest().build(); } } ``` 6. 程序运行后,在Vue上传图片即可自动将图片上传七牛云,并返回图片的访问URL。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值