vue+axios展示二进制文件流图片

409 阅读1分钟

1、请求方式

 axios({ url: '请求地址', responseType: 'arraybuffer', method: 'get/post', params: { ...data } })

2、展示方式

两种展示方式任意选择

1const url = URL.createObjectURL(new Blob([res]))     // 这种方法需要图片服务器不要添加限制

2const url = `data:image/png;base64,${btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`

在methods中对获取验证码的方法进行编写:

methods: {
    getImgCode () {
      this.$http.get('/后端接口', {
        responseType: 'arraybuffer'
      })
        .then(response => {
          return 'data:image/png;base64,' + btoa(
            new Uint8Array(response.data)
              .reduce((data, byte) => data + String.fromCharCode(byte), '')
          )
        }).then(data => {
          this.imgCode = data
        })
      console.log(this.imgCode)
    }

在data中:

data () { return { imgCode: '', } }, 在页面展示验证码:

<tr>
  <td>
<input type="imageCode" placeholder="验证码" v-model="form.imageCode">
  </td>
  <td>
<img :src="imgCode" style="cursor: poninter" @click="changeImgCode">
  </td>
</tr>