因為后端需要的是file: (binary)類型的文件,直接使用chooseImage方法返回的數據不符合要求,所以在使用該方法的基礎上,又調用了文件上傳的方法UploadImage,把文件上傳到服務器。
點擊按鈕,調用chooseImage
<button @click="chooseImage2"></button>
方法
chooseImage2
chooseImage2() {
let self = this
uni.chooseImage({
count: 1, //默認9
sourceType: ['album', 'camera'], //從相冊選擇、攝像頭
success: function(res) {
self.imgShow = res.tempFilePaths[0]
self.handleImage()
// uni.navigateTo({
// url: '../food/ingredient'
// });
}
});
}
handleImage:限制圖片大小,並調用上傳圖片的方法
async handleImage() {
if (this.imgShow.size / 1024 > 1024 * 5) {
// self.$api.msg("圖片大於5M,請重新上傳");
console.log("圖片大於5M,請重新上傳")
} else if (this.imgShow.size / 1024 > 1025) {
this.imgShow = await this.imgCompress(this.imgShow)
}
// this.$api.msg("服務器帶寬有限,圖片上傳較慢,請耐心等候!")
let uploadFileRes = await this.UploadImage(this.imgShow)
console.log(JSON.parse(uploadFileRes))
},
UploadImage:上傳圖片
UploadImage: (img) => {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: 'http://122.51.32.79:8004/hubu/food-info/identification-food',
filePath: img,
name: 'file',
success: (res) => {
resolve(res.data)
},
fail: (err) => {
reject('err')
}
});
})
}