WeChat H5 public account chooseImg upload pictures

The company's official account project was previously built using the Vant framework. In the first issue, I used the Uploader component provided by Vant to upload pictures. At that time, I didn’t mention to provide customers with the function of uploading multiple pictures, and the young lady who tested it had a very powerful iPhone at the beginning, and there were almost no problems.

The first phase is online, and the second phase is optimized. The key point is to provide multi-image uploading . The crash is that the Uploader component on the ios side is still very powerful as always, but it does not work at all on Android phones. I tried putting multiple at the end and assigning values ​​as netizens said, but it didn't evoke the multi-picture selection of Android.

<van-uploader :before-read="beforeRead" :after-read="afterRead" :before-delete="deletImg"
		:max-count="maxSize" v-model="fileList" multiple >
    <van-icon name="plus" />
</van-uploader>
设置成
<van-uploader :before-read="beforeRead" :after-read="afterRead" :before-delete="deletImg"
		:max-count="maxSize" v-model="fileList" :multiple="true">
	<van-icon name="plus" />
</van-uploader>

At this time, I found the uploader pit of Vant’s official website (some Androids don’t support it , laugh and cry~), I hope the next version can support it

I can only change the components. At this time, I think of WeChat's native chooseImage

WeChat encapsulates a series of methods chooseImage, previewImage, uploadImage, downloadImage, getLocalImgData for pictures , WeChat development document link: WeChat upload document

//拍照或从手机相册中选图接口
wx.chooseImage({
  count: 1, // 默认9
  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  success: function (res) {
  var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
  }
});

//预览图片
wx.previewImage({
  current: '', // 当前显示图片的http链接
  urls: [] // 需要预览的图片http链接列表
});

//图片上传,上传到微信的服务器
wx.uploadImage({
  localId: '', // 需要上传的图片的本地ID,由chooseImage接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    var serverId = res.serverId; // 返回图片的服务器端ID
  }
})

//下载图片
wx.downloadImage({
  serverId: '', // 需要下载的图片的服务器端ID,由uploadImage接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    var localId = res.localId; // 返回图片下载后的本地ID
  }
});

//获取本地图片
wx.getLocalImgData({
  localId: '', // 图片的localID
  success: function (res) {
    var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
  }
});

 1. I encapsulate the WeChat upload method used into a file. In the development process, we must first import the WeChat JSSDK file, and then register the required jsApi. When registering, call the backend interface to generate signature data

init(params,number,callback){
	    let config = null;
		getWxSign(params).then(res =>{
			if(res.code == 200){
				config = wxSign({ticket:res.content.ticket,appId:res.content.appid})
				wx.config({
				  debug: false, // 开启调试模式
				  appId: config.appId, //公众号的唯一标识
				  timestamp: config.timestamp, //生成签名的时间戳
				  nonceStr: config.nonceStr, //生成签名的随机串
				  signature: config.signature, //签名
				  jsApiList: ['chooseImage','uploadImage', 'downloadImage','getLocalImgData'], // 使用的JS接口列表
				});
				wx.ready(function(){
					wxUpload.chooseImage(number, callback);
				})
			}
		}).catch(error => {
			Toast(error);
		})
},

 2. Then call the method of WeChat to select photos, and invoke the function of WeChat to take pictures (select from the album)

chooseImage(number, callback){
	wx.checkJsApi({
		jsApiList: ['chooseImage'],
		success: function(res) {
			if(res.checkResult.chooseImage){
				wx.chooseImage({
					count: number,
					sizeType: ['original', 'compressed'], //是原图还是压缩图,默认二者都有
					sourceType: ['album', 'camera'], //来源是相册还是相机,默认二者都有
					success: function(res){
						Toast.loading({
							message: "加载中...",
							duration: 0,
							forbidClick: true
						})
						wxUpload.readImage(res.localIds, callback) //选定照片的本地ID列表
					},
					fail: function(error){
						Toast.clear();
					}
				})
			}
		}
	})
},

3. Obtain the local list of uploaded pictures, imageData is the last picture data you got from WeChat

readImage(localIds, callback){
	const imageData = []
	for(let i=0; i< localIds.length; i++){
		wx.getLocalImgData({
		    localId: localIds[i].toString(),
			success(res) {
				const localData = res.localData;
				let imageBase64 = '';
				if (localData.indexOf('data:image') == 0) {
					//ios直接赋值
					imageBase64 = localData;
				}else{
					//安卓在拼接前要进行换行符的全局替换
					imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
				}
				let fileData = wxUpload.dataURLtoFile(imageBase64);
				imageData.push(fileData)
				if(i == localIds.length-1){
					callback && callback(imageData)
				}
			},
			fail(res){
				Toast.clear();
			}
		})
	}
},

The overall function is not very complicated, but it is very difficult to debug. It must be uploaded to the server to see the effect. I hope you can share how to debug similar functions locally 

I uploaded the complete WeChat package upload function to my resource server, you can download it if you need it

This record is over, bye

Guess you like

Origin blog.csdn.net/codingLeader/article/details/123787814