前端将网页保存为图片,再发送给用户的流程

本文详细介绍了前端如何将网页内容保存为图片,然后通过上传至云端,调用后端接口获取mediaId,最后利用mediaId通过企业微信API发送图片给用户的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:将网页图片保存为图片
saveQrcode() {
      this.loadingFlag = true;
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      //你想要生成的图片的最外层div加一个id=qrCodeContainer
      let htmlDom = document.getElementById("qrCodeContainer");
      html2canvas(htmlDom, {
        backgroundColor: null, // null 表示设置背景为透明色
        width: htmlDom.clientWidth, //dom 原始宽度
        height: htmlDom.clientHeight,
        scrollY: 0,
        scrollX: 0,
        allowTaint: false,
        useCORS: true, // 解决需要生成的html中有img,生成的图片不显示
      }).then((canvas) => {
      //imgUrl是生成的base64,放到浏览器可直接查看图片,不过特别长,若调接口的时候传给后端,会有卡顿,所以将base64转成file文件
        const imgUrl = canvas.toDataURL("image/jpeg");
        //把base64转成file文件
        let picFile = this.dataURLtoBlob(imgUrl, "图片");
      	// 调用cos上传
        this.upload(picFile, "medAdvice/").then((res) => {
        //调接口获取MediaId,传参是图片url
          this.getMediaId(res.Url);
        });
      });
    },
将base64转换为blob(上面代码里要用到)
dataURLtoBlob(dataurl, fileName) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      var fileBlob = new Blob([u8arr], { type: mime });
      //将blob转换为file
      fileBlob.lastModifiedDate = new Date();
      fileBlob.name = fileName;
      return fileBlob;
    },
图片上传到COS上
upload(e,cosFilePath) {
        let _this = this;
        return new Promise((resolve, reject) => {
            var file = e;
            if (!file) return; // 分片上传文件
            let slotImgName = md5(file.name + new Date().getTime());
            _this.cos.putObject(
                {
                    Bucket: _this.cosKeyJson.bucket,
                    Region: _this.cosKeyJson.region,
                    Key: cosFilePath + slotImgName,
                    Body: file,
                    onProgress: function (progressData, callback) {
                        logger.log(JSON.stringify(progressData));
                    }
                },
                function (err, data) {
                    //下面这个方法是vue中获取你上传成功后的Url地址,别人可以通过这个地址来查看,下载你上传的文件
                    _this.cos.getObjectUrl(
                        {
                            Key: cosFilePath + slotImgName,
                            Bucket: _this.cosKeyJson.bucket,
                            Sign: false,
                            Region: _this.cosKeyJson.region
                        },
                        function (err, data) {
                            resolve(data);
                            reject(err);
                        }
                    );

                }
            )
        });

    };
第二步:用调后端接口,传参是图片(看后端需要什么格式,需要base64格式则传上面的imgUrl,若需要file文件格式,则传上面的picFile),获取mediaId。
getMediaId(url) {
      let needData = {
        fileStream: url, //图片URL
      };
      BaseHttpS.uploadFileToWeChat(needData).then((res) => {
        if (res.data.code == "0000000") {
          console.log('前端拿到的mediaId:',res.data.data)
          //调发送图片接口,传参是mediaId,发送给用户
          this.sendQRcode(res.data.data);
        } else {
          this.loadingFlag = false;
          this.$toast.fail(res.data.message);
        }
      });
    },
第三步:调发企业微信API,使用mediaId把图片发送给用户
sendQRcode(mediaId) {
      var local = location.href.split("#")[0]; // 获取页面url
      let params = {
        url: local,
      };
      BaseHttpS.qiyeWeiXinUrlSignature(params).then((res) => {
        this.loadingFlag = false;
        let sdkConfigInfo = res.data.data;
        wx.config({
          beta: true, // 必须这么写,否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId: sdkConfigInfo.corpid, // 必填,企业微信的corpID
          timestamp: sdkConfigInfo.timestamp, // 必填,生成签名的时间戳
          nonceStr: sdkConfigInfo.nonceStr, // 必填,生成签名的随机串
          signature: sdkConfigInfo.signature, // 必填,签名,见附录1
          jsApiList: [
            "getCurExternalChat",
            "sendChatMessage",
            "openEnterpriseChat",
          ], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
          openTagList: ["wx-open-launch-weapp"], // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
          success: function (res) {
            // 回调
          },
          fail: function (res) {
            if (res.errMsg.indexOf("function not exist") > -1) {
              _this.$toast.fail("版本过低请升级");
            }
          },
        });
        wx.ready(function () {
          wx.agentConfig({
            corpid: sdkConfigInfo.corpid, // 必填,企业微信的corpID
            agentid: sdkConfigInfo.agentid, // 必填,企业微信的应用id (e.g. 1000247)
            timestamp: sdkConfigInfo.timestamp, // 必填,生成签名的时间戳
            nonceStr: sdkConfigInfo.nonceStr, // 必填,生成签名的随机串
            signature: sdkConfigInfo.signatureAgent, // 必填,签名,见附录1
            jsApiList: [
              "getCurExternalChat",
              "sendChatMessage",
              "openEnterpriseChat",
              "getCurExternalContact",
            ], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            success: function (res) {
              // 跳转到 企业微信的 对话框
              wx.invoke(
                "sendChatMessage",
                {
                  msgtype: "image", //消息类型,必填
                  image: {
                    mediaid: mediaId, //图片的素材id
                  },
                },
                function (res) {
                  console.log("sendChatMessage==" + res);
                  if (res.err_msg == "sendChatMessage:ok") {
                    //发送成功
                  }
                  console.log(res);
                }
              );
            },
            fail: function (res) {
              if (res.errMsg.indexOf("function not exist") > -1) {
                _this.$toast.fail("版本过低请升级");
              }
            },
          });
        });
        wx.error(function (res) {
          console.log(res, "error - config");
        });
      });
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值