uni-app、后端直接返回图片正确的处理方式、避免踩坑

726 阅读1分钟

一、添加响应类型为arraybuffer

export const getVerifyCode = (params) => {
	return http.get(`${url}/VerifyCode`, {
		params,
		responseType: "arraybuffer"
	});
};

二、用uni-app的内置方法arrayBufferToBase64

将arraybuffer类型的响应数据转为base64

uni.arrayBufferToBase64(arrayBuffer);

三、拼接并赋值给自己定义的变量

this.imgUrl = 'data:image/png;base64,' + uni.arrayBufferToBase64(arrayBuffer);

四、完整代码

<template>
    <image
	:src="imgUrl"
	@click="getCaptcha"
    />
</template>
<script>
import { getVerifyCode } from '@/api/account/index.js';
export default {
  data() {
	return {
	   imgUrl:''
	}
   },
   onLoad() {
      this.getCaptcha();
   },
   methods:{
      async getCaptcha(){
	const verifyId = new Date().getTime();
	const arrayBuffer = await getVerifyCode({verifyId});
	this.imgUrl = 'data:image/png;base64,' + uni.arrayBufferToBase64(arrayBuffer);
      }
   }
}
</script>

每天进步一点点,欢迎评论区交流🤭!!!