Vue 实现 上传图片 二维码识别 + 条形码识别(qrcode-decoder插件)

需求

1.web端H5 实现 上传图片 自动识别二维码内容

2.具体业务 比如 上传电影票 自动识别取票码或者其他的二维码上传(主要是为增加用户体验)

二维码(插件):

1.使用Npm安装qrcode-decoder

npm i qrcode-decoder --registry=https://registry.npm.taobao.org

2.创建一个方法 qrcode.js

// 引入qrcode-decoder,
// import QrCode from 'qrcode-decoder'
// 部分网友反应上面的引入,这个引入的是一个空对象,不能使用,已经给开发者提issues了,希望能尽快修复不能使用或报错,可以试试下面这种
import QrCode from '../../../../../node_modules/qrcode-decoder/dist/index';
// 传入file对象,返回promise
export function getQrUrl(file) {
    //使用这个方法或者下面被注释的方法设置浏览器读取文件方式,chrome和ie有效,其他浏览器没测试
    const URi = window.webkitURL.createObjectURL(file) || window.URL.createObjectURL(file)
    // if (window.webkitURL) {
    //     URi = window.webkitURL.createObjectURL(file);
    // } else if (window.URL && window.URL.createObjectURL) {
    //     URi = window.URL.createObjectURL(file);
    // } else {
    //     URi = null;
    // }
    const url = URi
    // 初始化
    const qr = new QrCode()
    // 解析二维码,返回promise
    return qr.decodeFromImage(url)
}

3.在页面上使用

const handleFileChange = (event, index) => {
  console.log(event, index);

  console.log(
    event.target.childNodes[0].files[0],
    "event.childNodes.childNodes.files"
  );
  // onFileChange(event.target.childNodes[0].files[0], index);
  handleUpload(event.target.childNodes[0].files[0], index);

  // onFileChange(event.target.childNodes[0].files[0]);

  const result = getQrUrl(event.target.childNodes[0].files[0])
  result.then(res => {
    console.log(res);
    if (res.data) {
      console.log(res.data, '二维码内容')
      if (res.data.length > 12) {
        imageList[index].code = res.data
        if (res.data.indexOf("|") != -1 && res.data.length > 12) {
          var str = res.data.split("|")
          imageList[index].code = str[0]
          imageList[index].yanz = str[1]
        }
      } else if (res.data.indexOf("|") == -1 && res.data.length == 12) {
        imageList[index].code = res.data.slice(0, 6)
        imageList[index].yanz = res.data.slice(6)
      } else if (res.data.indexOf("|") == -1 && res.data.length < 12) {
        imageList[index].code = res.data
        imageList[index].yanz = ""
      }
      //   Toast('识别二维码成功!')
    } else {
      Taro.showToast({
        title: "识别失败,请重新上传",
        icon: "none",
        duration: 2000,
      })
    }
  })
};

我的这个方法是上传图片的 获取的参数是file 在你们的那里可能不一样 根据你们的实际需求去调整

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值