其他分享
首页 > 其他分享> > html2canvas图片生成file格式传送到后台服务器

html2canvas图片生成file格式传送到后台服务器

作者:互联网

1.首先将html保存为base64图片

html2canvas.js(可在各cdn进行下载)
eg: cdn.bootcss.com/html2canvas…

html2canvas百度一下代码很多,这里废话不多说,直接上代码
因为是将html里部分保存为图片,所以以下代码实现的是全屏画布上展示需要的部分

    var canvas1 = document.createElement("canvas");
    let _canvas = document.querySelector('.resDetailRight');//目标块
    var bodyW = parseInt(window.getComputedStyle(document.querySelector('html')).width)
    var bodyH = parseInt(window.getComputedStyle(document.querySelector('html')).height)
    var footH = parseInt(window.getComputedStyle(document.querySelector('.recommend-resume')).height) //多余部分
    console.log('canvas:', bodyW, bodyH)
    //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
    canvas1.width = bodyW * 2;
    canvas1.height = (bodyH - footH) * 2;
    canvas1.style.width = bodyW + "px";
    canvas1.style.height = bodyH - footH + "px";
    //关于截取不全的操作,点击触发时需要从顶部获取,故在此将页面滚动到顶部然后在执行
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    var context = canvas1.getContext("2d");
    context.scale(2, 2);
    html2canvas(_canvas, {
      canvas: canvas1
    }).then(function (canvas) {
       //document.body.appendChild(canvas); //直接在底部展示该图
       file = canvas.toDataURL("image/png");
       //canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载
       // document.querySelector(".down").setAttribute('href', canvas.toDataURL());
    });

2.将获取的图片转换为文件格式

    dataURLtoFile(dataURI, type) {
	let binary = atob(dataURI.split(',')[1]);
	let array = [];
	for(let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
	}
	return new Blob([new Uint8Array(array)], {type:type });
    }

3.通过ajax将文件传给后端服务器

    var formData = new FormData();
    let blob= dataURLtoFile(file, 'image/jpeg')
    let fileOfBlob = new File([blob], new Date()+'.jpg')
        formData.append('file', fileOfBlob);
        $.ajax({
        url: "/gateway/system/plug/resume/upload",
        type: "post",
        data: formData,
        headers:{
           'Authorization':'bearer '+sessionStorage.getItem("token")
        },
        contentType: false,
        processData: false,
        success: function (res) {
            let resumeInfo = res.result
		//sendResumeInfo(tabId, resumeInfo)
		checkRepeat(tabId, JSON.stringify(resumeInfo))
        },
        error: function (data) {
            alert("上传失败")
            }
       });

至此功能开发完成。

标签:canvas,html2canvas,let,file,var,服务器,canvas1,document
来源: https://blog.csdn.net/qq_29528701/article/details/120163572