截图上传服务器的前端vue2代码

一、安装html2canvas和moment

npm install html2canvas --save
npm install moment --save

二、引入html2canvas和moment

import html2canvas from "html2canvas";
import moment from "moment";

三、data部分

data() {
    return {
    	formData: null,
    }
}

四、methods部分代码(先调用截图的方法,然后调用上传服务器的方法,)

	takeScreenshot() {
      this.formData = null;
      try {
        const el = document.querySelector("html");
        html2canvas(el, { allowTaint: true }).then((canvas) => {
          // 获取canvas对应的Base64编码的图片数据
          const base64Data = canvas.toDataURL("image/png");

          // 将Base64数据转换为File对象
          const file = this.dataURLToFile(
            base64Data,
            moment().format("YYYY-MM-DD HH:mm:ss") + `.png`
          );

          // 创建FormData对象并添加文件
          const formData = new FormData();
          formData.append("file", file);

          //先返回,然后手动调用上传(不立即上传)
          this.formData = formData;
        });
      } catch (error) {
        console.error("截屏或上传出现错误:", error);
      }
    },
    dataURLToFile(dataurl, filename) {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },

    async uploadFile(formData) {
      this.$axios
        .post("http://app.hrbbrg.online:10666/upload", formData, 
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          if (response.data.code == 200) {
            this.$axios
              .get("http://10.57.20.70/api", {
                params: {
                  model: this.objList.model + this.objList.type,
                  url: response.data.obj,
                  fileName: response.data.name,
                },
              })
              .then((res) => {
                if (res.data.code == 200) {
                  console.log("图片上传成功");
                } else {
                  console.error("图片上传失败", response.status);
                }
              });
          } else {
            console.error("图片上传失败,状态码:", response.status);
          }
        });
    },

五、调用方法执行

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值