图片三种访问方式:
1. 返回的是图片url字符串 src=“http://xxxxx.jpg”
2. 返回的是图片类型的文件流 返回contentType的是image/png类型的,就new Blob对象,然后取blob对象中的url,图片上传组件选取本地图片能显示图片用的是该原理
3. 返回的是图片的二进制缓冲流,contentType为arrayBuffer,因为二进制是最原始的数据,所以可以转成任意流存储,如图片类型的文件流,图片的base64
小程序没用第二种方式是因为小程序没有Blob这个对象,所以图片只能是arrayBuffer(二进制缓冲流)转成base64然后访问
以下为uniapp项目中封装的方法
后端返回的路径,拼成需要的格式,再将url转成base64
//获取图片二进制数据
export const getImageBase64 = ({ url, id }) => {
let baseUrl = REQUEST.BASE_URL
return new Promise((resolve, reject) => {
uni.request({
url: `${baseUrl}${url}?id=${id}`,
header: {
userMiniAccessToken: uni.getStorageSync('accessToken'),
'content-type': 'application/json'
},
responseType: 'arraybuffer',
method: 'GET',
success: function (res) {
resolve('data:image/png;base64,' + uni.arrayBufferToBase64(res.data))
},
fail: function (err) {
reject('')
}
})
})
}
// 调用
getImageBase64({
url: '/auth/show/photos/ua',
id: item.id
}).then(res => {
console.log('拿到图片路径',res)
})
微信小程序端
export const imageBase64 = (id) => {
console.log(app.globalData.imgHost + '/api/auth/show/photos/ua?id=' + id);
return new Promise((resolve, reject) => {
wx.request({
url: app.globalData.imgHost + '/api/auth/show/photos/ua?id=' + id,
header: {
userMiniAccessToken: wx.getStorageSync('accessToken'),
'content-type': 'application/json',
},
responseType: 'arraybuffer',
method: 'GET',
success: function (res) {
resolve('data:image/png;base64,' + wx.arrayBufferToBase64(res.data))
},
fail: function (err) {
reject('')
}
})
})
}
// 使用
async channelBusinessCheck() {
let res = await accCenter.supplierBusinessCheck()
let { code, message,data } = res.data
if (code == 2000) {
let certificateList = []
for (let i = 0; i < data.certificate.length; i++) {
console.log(imageBase64(data.certificate[i].id));
let obj = {
name: data.certificate[i].fileNid,
url: await imageBase64(data.certificate[i].id),
type: 'image',
fromNet: true,
}
certificateList.push(obj)
}
data.certificateList = certificateList
this.setData({
formData: data,
})
} else {
wx.showToast({
title: message || '程序出错啦',
icon: 'none',
})
}
},
将拼好的路径通过封装的方法发get请求
最终得到的base64格式图片如下: