index.vue 3.02 KB
<!--
 * @Date: 2022-09-06 16:29:31
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2022-09-07 00:46:48
 * @FilePath: /data-table/src/components/SignField/index.vue
 * @Description: 文件描述
-->
<template>
  <div class="sign-page">
    <div class="label">{{ item.label }}<span v-if="item.required">&nbsp;*</span></div>
    <div style="padding: 1rem;">

      <vue-esign ref="esign" style="border: 1px dashed #c2c1c1;" :height="700" :isCrop="isCrop" :lineWidth="lineWidth"
        :lineColor="lineColor" :bgColor.sync="bgColor" />
    </div>
    <div class="control-sign">
      <button @click="handleReset">清空画板</button>
      <button @click="handleGenerate">生成图片</button>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  item: Object
});
</script>

<script>
import { v4 as uuidv4 } from 'uuid';
import { qiniuTokenAPI, qiniuUploadAPI, saveFileAPI } from '@/api/common'

export default {
  data() {
    return {
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "",
      resultImg: "",
      isCrop: false,
    }
  },
  methods: {
    //清空画板..
    handleReset() {
      this.$refs.esign.reset();
      this.resultImg = "";
    },
    //生成签名图片..
    handleGenerate () {
      this.$refs.esign.generate()
        .then(async res => {
          // let fileName = "img1.png";
          // let file = this.dataURLtoFile(res, fileName);
          // console.log("file", file);
          let affix = uuidv4();
          let base64url = res.slice(res.indexOf(',') + 1);  // 截取前缀的base64   data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAnoAAAJeCAYAA.......
          // 获取七牛token
          const { token, key, code } = await qiniuTokenAPI({ filename: `${affix}_sign`, file: base64url });
          if (code) {
            const config = {
              headers: {
                'Content-Type': 'application/octet-stream',
                'Authorization': 'UpToken ' + token,    // UpToken后必须有一个 ' '(空格)
              }
            }
            // 上传七牛服务器
            const { filekey, hash, image_info } = await qiniuUploadAPI('http://upload.qiniup.com/putb64/-1/key/' + key, base64url, config)
            if (filekey) {
              // 保存图片
              const { data } = await saveFileAPI({ filekey, hash, format: image_info.format, height: image_info.height, width: image_info.width });
              console.warn(data.src);
            }
          }
        });
    },
    //将图片base64转换为文件
    dataURLtoFile(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);
      }
      return new File([u8arr], filename, { type: mime });
    }
  }
}
</script>

<style lang="less" scoped>
.sign-page {
  .label {
    padding: 1rem 1rem 0 1rem;
    font-size: 0.9rem;
    font-weight: bold;

    span {
      color: red;
    }
  }
}
</style>