Screenshot of VUE+html2canvas page and upload to the background for saving

1. First download html2canvas

npm install html2canvas

2. html select screenshot area and event click

<div ref="table"></div>//截图区域
<el-button type="info" size="mini" @click="saveImg">保存图片</el-button>

3. The method of page JS reference and save upload

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. The backend receives the file and saves it

    @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();


	}

 

Guess you like

Origin blog.csdn.net/qq_36802726/article/details/110624402