js 解决获取图片乱码 将 Arraybuffer 转换为 base64 的两种方式

效果

在这里插入图片描述

请求

axios 添加 responseType: ‘arraybuffer’

 axios 
    .get('/Base/captcha?' + Math.random(), {
    
    }, {
    
     responseType: 'arraybuffer' })

Arraybuffer 转换为 base64 方式一 window.btoa (已弃用)

 const base64Str = 'data:image/png;base64,' +
       btoa(
         new Uint8Array(response).reduce(
           (data, byte) => data + String.fromCharCode(byte),
           ''
        )
       )

Arraybuffer 转换为 base64 方式二 window.Buffer.from 及window.buffer.toString

const buffer = Buffer.from(response, 'base64')
const base64Str =  'data:image/png;base64,' + buffer.toString('base64')

vue3 vite 使用 方式一

猜你喜欢

转载自blog.csdn.net/weixin_43245095/article/details/124381680