uniapp: this.$request是自己封装的 uni.request函数,responseType也需要写入封装函数,具体见uniapp请求封装

<template>
  <view>
    <!-- 显示图片的位置-->
    <image :src="QRImg"></image>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        QRImg: '',
      }
    },
    methods: {
      //获取图片
      async getImg() {
        const res = await this.$request('请求的url', {
          data: {
            "tablesid": this.orderId,
          },
          responseType: "arraybuffer", //这是必要的一步,responseType必须设置为arraybuffer
        })
        console.log(res, "kdkdkd")
        const arrayBuffer = res.data
        //将arrayBuffer数据转换成base64格式即可显示
        this.QRImg = `data:image/jpeg;base64,${uni.arrayBufferToBase64(arrayBuffer)}`
      },
    }
</script>

vue: 请求方法用的是axios的get方法

<template>
  <div>
    <img :src="QRImg" alt=""/>
  </div>
</template>
<script>
export default {
  data() {
    return {
      QRImg: '',
    }
  },
  method() {
    //获取图片
    async getQrCode() {
      const {token, storeid} = this.userInfo
      const config = {responseType: 'arraybuffer'}
      let res = await getData(`你的url`, config);
      // console.log(res,"res-----")
      this.qrImg = `data:image/jpeg;base64,${this.arrayBufferToBase64(res)}`
    } ,
    //转换图片编码
    arrayBufferToBase64(buffer) {
      let binary = ''
      let bytes = new Uint8Array(buffer)
      let len = bytes.byteLength
      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i])
      }
      return window.btoa(binary)
    } ,
  }
}
</script>

总结:uniapp 和vue的方法异曲同工,不同的可能就是标签写法的差异,还有uniappy已经封装好了图片转码的api,总的来说就是responseType为arraybuffer,然后再将结果转换为base64

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐