html2canvas页面转成图片可保存可上传--运维系统shpc.yunweiguanli.pc

 https://blog.csdn.net/weixin_43288600/article/details/121430649

安装
npm i html2canvas

//需要引用的页面

import html2canvas from 'html2canvas';


//使用方法:使用div包裹一下,并且ref命名
<div ref="imgBox">
//此处是需要保存图片的内容
</div>

// 保存并上传图片
const imgBox: any = ref(null)
const saveImage = async () => {
  console.log(imgBox.value)
  userCountList.value = [];
  loginedCountList.value = [];
  handledCountList.value = [];
  report.value.userCountFilePath = '';
  report.value.loginedCountFilePath = '';
  report.value.handledCountFilePath = '';


  await html2canvas(imgBox.value, {
    height: imgBox.value.scrollHeight,
    width: imgBox.value.scrollWidth,
  }).then((canvas) => {
    const link = document.createElement("a"); // 创建一个超链接对象实例
    link.download = "image.png"; // 设置要下载的图片的名称
    link.href = canvas.toDataURL(); // 将图片的URL设置到超链接的href中
    console.log(link.href)
    //通过模拟连接的形式,打开并保存图片
    //link.click(); // 触发超链接的点击事件,将图片保存到本地

    //将图片上传至服务器
    var imgData = canvas.toDataURL('image/png');
   //将base64的图片转成blob,再转换成文档流,进行上传
    var blob = dataURLtoBlob(imgData);
    var file = new File([blob],new Date().getTime()+".png");

        const formData = new FormData()
        formData.append('file', file)
        axios.post("api/YW/UploadFile", formData, {   //以文档流的方式上传
          headers: {
            "Content-Type": "multipart/form-data"
          }
        }).then(response => {
          sqlShow.value = false;
          sqlLoading.value=false;
          userCountList.value.push({  //将返回的值重新赋值给原有的组件
            url: response.data.url,
            name: 'userCount',
          });
          loginedCountList.value.push({
            url: response.data.url,
            name: 'loginedCount',
          });
          handledCountList.value.push({
            url: response.data.url,
            name: 'handledCount',
          });
          report.value.userCountFilePath = response.data.url;   //将返回的url赋值给要提交的 report.value
         report.value.loginedCountFilePath = response.data.url; 
report.value.handledCountFilePath
= response.data.url;
}).
catch(error => { console.error(error); });
});
}

 原文:https://blog.csdn.net/weixin_43288600/article/details/121430649

posted @ 2024-07-26 15:39  Shimily  阅读(42)  评论(0)    收藏  举报