wx上传图片以及转base64

wx图片

  • 转base64
piceImg(){
	this.pics = []
	let that = this
	const fileManager = wx.getFileSystemManager();
	// that.imageList图片数组[{piceUrl:''}]
	for(let rfd of that.imageList){
		// console.log(rfd.piceUrl)
		// 判断是本地上传的还是https回显的
		if(rfd.piceUrl && rfd.piceUrl.split('/upload')[1]){
			// https回显
			wx.downloadFile({
				url: rfd.piceUrl,
				success(res) {
					// console.log(res.tempFilePath)
					let base64 = fileManager.readFileSync(res.tempFilePath, 'base64');
					that.pics.push('data:image/png;base64,'+base64+')')
				},
				fail(res){
					uni.showToast({
						title: '图片不在域列表中'+JSON.stringify(res),
						icon: 'none'
					})
				}
			})
			// that.pics.push(rfd.piceUrl)
		} else if(rfd.piceUrl) {
			// 本地上传
			let base64 = fileManager.readFileSync(rfd.piceUrl, 'base64');
			that.pics.push('data:image/png;base64,'+base64+')')
		}
	}
	// console.log(that.pics)
}
  • 查看图片
previewImage(index) {
	let imgs = []
	this.imageList.forEach(item=>{
		// 判断是否有图片
		if(item.piceUrl){
			imgs.push(item.piceUrl)
		}
	})
	uni.previewImage({
		current: index,// 下标1,就是重1开始
		urls: imgs
	})
}
  • 上传图片
    图片显示数组imageList
addPicture(index){
	let that = this;
	uni.chooseImage({
		count: 3, //默认9,最多上传数量,最多可一次选3张
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album', 'camera'], //从相册选择
		success: function (res) {
			// 第1个上传框(最多三个框)
			if(index == 0){
				that.imageList[0].piceUrl = res.tempFilePaths[0]
				if(res.tempFilePaths.length == 1 || res.tempFilePaths.length == 2){
					that.imageList.push({piceUrl:''})
				}else{
					for(let i in res.tempFilePaths){
						if(i>0){
							that.imageList.push({piceUrl:res.tempFilePaths[i]})
						}
					}
				}
			}else if(index == 1){// 第2个上传框
				that.imageList[1].piceUrl = res.tempFilePaths[0];
				if(res.tempFilePaths.length>1){
					that.imageList.push({piceUrl:res.tempFilePaths[1]})
				}else if(res.tempFilePaths.length == 1){
					that.imageList.push({piceUrl:''})
				}
			}else{
				that.imageList[index].piceUrl = res.tempFilePaths[0];
			}
			that.piceImg()// 转base64
		},
		fail () {
		    wx.showToast({
		      title: '获取图片失败',
			  icon: 'none',
		      duration: 2000
		    })
		}
	});
}
  • 图片单个删除
imageDel(index) {
	this.imageList.splice(index,1)
}

你可能感兴趣的:(微信图片)