vue高拍仪拍照后上传服务器回显到Upload(记录)

这是一个关于使用H5实现高拍仪拍照并上传至服务器的组件示例。通过调用电脑摄像头,选择高拍仪设备,捕获视频帧,将图像渲染到canvas上,然后转换为base64格式并上传到服务器。同时,提供了关闭摄像头和图片预览的功能。
摘要由CSDN通过智能技术生成

1.子组件(高拍仪的拍照和上传服务器)

<template>
  <div class="photoClass">
    <div class="upPhotoClass" @click="upPhotoFn" />
    <el-dialog :visible.sync="dialogVisible" :modal="false" width="30%" :show-close="false">
      <canvas v-show="false" ref="canvas" width="400" height="400" />
      <video ref="video" width="400" height="400" autoplay />
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="photograph">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { apiUpload } from '@/api/index.js'
export default {
  props: {
    edits: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      camera: '',
      imgSrc: ''
    }
  },
  computed: {},
  methods: {
    //点击弹出高拍仪摄像头
    upPhotoFn() {
      if (!this.edits) {//是否可以点开dialog
        return
      }
      this.dialogVisible = true
      this.getAllCamera()
    },
    handleClose() {
      this.closeCamera()
      this.dialogVisible = false
    },
    // 获取摄像头
    getAllCamera() {
      navigator.mediaDevices
        .enumerateDevices()
        .then(this.gotDevices)
        .then(this.callCamera)
        .catch(this.handleError)
    },
    // 选择摄像头
    gotDevices(deviceInfos) {
      console.log(deviceInfos)
      const options = []
      for (var i = 0; i < deviceInfos.length; ++i) {
        var deviceInfo = deviceInfos[i]
        var option = document.createElement('option')
        option.value = deviceInfo.deviceId
        if (deviceInfo.kind === 'videoinput') {
          options.push({
            value: deviceInfo.deviceId,
            label: deviceInfo.label
          })
        } else {
          // console.log('Found ome other kind of source/device: ', deviceInfo);
        }
      }
      this.camera = options[1].value//options[1]高拍仪第二个摄像头,第一个写为options[0]
    },
    // 调用摄像头错误
    handleError(error) {
      this.$message.error(error.name + ': ' + error.message)
    },
    // 调用摄像头
    callCamera() {
      // this.getAllCamera();
      // H5调用电脑摄像头API
      navigator.mediaDevices
        .getUserMedia({
          // video: true,
          video: {
            optional: [
              {
                sourceId: this.camera
              }
            ]
          }
        })
        .then(success => {
          // console.log(success);
          // 摄像头开启成功
          this.$refs['video'].srcObject = success
          // 实时拍照效果
          this.$refs['video'].play()
        })
        .catch(error => {
          this.$message.error(
            '摄像头开启失败,请检查摄像头是否可用并重新打开!'
          )
        })
    },
    // 关闭摄像头
    closeCamera() {
      if (!this.$refs['video'].srcObject) {
        this.dialogVisible = false
        return
      }
      const stream = this.$refs['video'].srcObject
      const tracks = stream.getTracks()
      tracks.forEach(track => {
        track.stop()
      })
      this.$refs['video'].srcObject = null
      // this.$emit('closeCamera')
    },
    //拍照
    photograph() {
      const ctx = this.$refs['canvas'].getContext('2d')
      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs['video'], 0, 0, 400, 400)
      // 转base64格式、图片格式转换、图片质量压缩
      // let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)
      const imgurl = this.$refs['canvas'].toDataURL('image/png')
      this.imgSrc = imgurl
      console.log(imgurl)
      this.onUpload()
    },
    onUpload() {
      const file = this.imgSrc // 把整个base64给file
      const time = new Date().valueOf() // 生成时间戳
      const name = time + '.png' // 定义文件名字(例如:abc.png , cover.png)
      const conversions = this.dataURLtoFile(file, name) // 调用base64转图片方法
      const data = new FormData()
      data.append('file', conversions)
      apiUpload(data).then(res => {//上传到服务
        console.log(res)
        if (res.code == 200) {
          this.$emit('changPhotoFn', res.data)//返回值传给父组件
        }
      })
        .catch((e) => {
          console.log(e)
        })
      this.closeCamera()
      this.dialogVisible = false
    },
    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    }
  }
}
</script>

<style scoped>
.photoClass {
  width: 120px;
  height: 120px;
}
.upPhotoClass {
  width: 100%;
  height: 100%;
  border: 1px dotted #d9d9d9;
}
.photoDialogClass {
  /* height: 300px; */
}
</style>

2.父组件

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回显Vue上传组件的文件列表可以通过绑定file-list属性来实现。在给el-upload组件绑定file-list属性时,可以将一个数组作为值传递给file-list属性,数组中的每个元素代表一个文件对象,包含文件的相关信息,如文件名、文件地址等。在Vue的data中定义一个fileList数组,然后将该数组绑定到el-upload的file-list属性上即可实现回显。例如,可以将fileList绑定到el-upload的file-list属性上,如下所示: <el-upload :file-list="fileList" ...></el-upload> 其中,fileList是一个数组,包含了要回显的文件对象的信息。你可以在Vue的data中定义fileList数组,并将其初始化为空数组。然后,通过某种方式将要回显的文件对象添加到fileList数组中,例如在上传成功后将文件对象添加到fileList数组中。这样,当页面加载时,el-upload组件就会根据fileList数组中的文件对象来回显文件列表。 请注意,回显文件列表时,需要确保每个文件对象的属性与el-upload组件的要求相匹配,例如文件名属性为name,文件地址属性为url等。你可以根据实际情况调整文件对象的属性名,以使其与el-upload组件的要求相符。 希望这个回答对你有帮助。如果你还有其他问题,请随时提问。 #### 引用[.reference_title] - *1* *2* *3* [【vue 项目】el-upload 上传文件以及回显照片和下载文件](https://blog.csdn.net/Aohanzzz/article/details/129378829)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值