Problem Description
The front desk needs to display the picture, and the background is expected to return the picture address directly, but the backstage gives the file stream instead of a picture address, and the file stream needs to be displayed in base64 format.
When requesting the back-end interface, the content of the returned picture is as follows: The picture
above is not in base64 format, and the file stream data is twenty binary. If the front-end wants to display, only need to convert the data format to base64.
Solution
- Need to add responseType: "arraybuffer" in the interface for getting pictures
getVerifyCode({
tel = '',
}) {
// 获取图形验证码
return request({
url: 'test/xxx/xxx',
method: 'post',
data: Object.assign({
username: tel
}, commonquery()),
responseType: 'arraybuffer'
})
},
The interface after setting responseType:'arraybuffer' returns:
- Add an img tag where you need to display the picture
<img
:src="verifyImg"
@click="getVerify"
/>
- Base64 conversion display
Assignment to verifyImg variable bound to src
getVerify() {
inviteApi["getVerifyCode"]({
tel: this.tel
})
.then(res => {
const src =
"data:image/png;base64," +
btoa(
new Uint8Array(res.data).reduce(
(data, byte) => data + String.fromCharCode(byte),
""
)
);
this.verifyImg = src;
})
.catch(error => {
console.log(error);
});
},
- The picture finally displayed on the front-end page is shown in the following figure.
Reference: The front-end converts the picture file to base64 format and displays it on the front-end, displaying the picture