VUE+html2canvas 页面截图并上传到后台进行保存

1、首先进行html2canvas下载

npm install html2canvas

2、html选取截图区域和事件点击

//截图区域 保存图片

3、页面JS引用和保存上传的方法

import html2canvas from 'html2canvas'


//方法
    saveImg() {
      html2canvas(this.$refs.table, {
        useCORS: true,
        backgroundColor: null
      })
        .then(canvas => {
          const dataUrl = canvas.toDataURL('images/jpg')
          // 第一步:将dataUrl转换成Blob
          var fd = new FormData()
          var blob = this.dataURItoBlob(dataUrl)
          fd.append('file', blob, Date.now() + '.jpg')          
          // 第二步:上传分享图
          this.$http.post('test', fd).then((res) => {

          })
        })
    },
    dataURItoBlob (dataURI) { // base64转buffer
      var byteString = atob(dataURI.split(',')[1])
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
      var ab = new ArrayBuffer(byteString.length)
      var ia = new Uint8Array(ab)
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ab], { type: mimeString })
    },

4、后端接收文件并进行保存

    @PostMapping("test")
    @ApiOperation("测试")
    public R test(@RequestParam("file") MultipartFile file){
		System.out.println(file);
		String fileName = file.getOriginalFilename();
		if(fileName.indexOf("\\") != -1){
			fileName = fileName.substring(fileName.lastIndexOf("\\"));
		}
		String filePath = "src/main/resources/static/files/";
		File targetFile = new File(filePath);
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(filePath+fileName);
			out.write(file.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}
		return R.ok();


	}

 

你可能感兴趣的:(html,java,vue.js)