uni調用chooseImage方法上傳base64圖片


因為后端需要的是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')
						}
					});
				})
			}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM