图片显示(后端返回接口在预览中展示图片,响应无返回)后端返回二进制图片前端乱码解决方案
https://blog.csdn.net/weixin_46801282/article/details/123386264
// base64数据
this.imgSrc = 'data:image/jpg;base64,' + res.payload.imageStr;
解决方案一:
后端把图片转码成base64再发送过来
router.get('/test', (req, res) => {
fs.readFile('./test.png', 'binary', function (err, file) {
if (err) {
console.log(err)
return
} else {
res.send({
status: 0,
message: '调取成功',
data: Buffer.from(file, 'binary').toString('base64'),
})
}
})
})
解决方案二
添加 {responseType: ‘arraybuffer’} 请求头,获取ArrayBuffer类型数据,再转码成base64
axios.get('http://localhost:801/my/test', {
responseType: 'arraybuffer'
}).then(res => {
console.log(res)
// buffer转译
console.log(btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')), 'base64');
})
解决方案三
跟前面方法二一样
添加 {responseType: ‘blob’} 请求头,获取blob类型数据
axios.get('http://localhost:801/my/test', {
responseType: 'blob'
}).then(res => {
console.log(
res
)
const blob = new Blob([res.data])
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
document.querySelector('#img').src = reader.result
}
})
浙公网安备 33010602011771号