最近用uniapp写一个图片上传功能,并且需要展示从后台获取到的图片
如图
实现上传后后台返回数据并立即更新图片
源代码如下
// 上传头像
imgUp(val) {
let that = this
uni.chooseImage({
sizeType: ['original'],
count: 1,
success: function(res) {
const tempFilePaths = res.tempFilePaths
uni.uploadFile({
url: that.$serverUrl + "member/up",
filePath: tempFilePaths[0],
formData:{
token:that.token,
id:that.userId,
ttid:8,
myimg:that.myimg
},
name: 'file',
success: (res) => {
const data = JSON.parse(res.data)
that.myimg=data.url
}
})
// this.headPortrait=
}
});
},
注意,uni.uploadFile()返回后的数据是字符串类型,运用json.parse()转化为json。这时问题来了,h5可以正常实现,但是app会报错而且无法转化
解决方法:在json转化之前用replace方法去掉字符**\ufeff**即可