uni-app调用微信公众号 上传接口并上传到自己的服务器(base64转图片格式)

async function uploadImage(count = 3) {

	try {

		let ajax = new api()
		var htmlUrl = location.href;
		let data = await ajax.request(url.getWxJs, {
			url: htmlUrl
		})

		let result = data.data

		wx.config({
			debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印。
			appId: result.appID, // 必填,公众号的唯一标识
			timestamp: result.timestamp, // 必填,生成签名的时间戳
			nonceStr: result.noncestr, // 必填,生成签名的随机串
			signature: result.signature, // 必填,签名
			jsApiList: ['chooseImage', 'getLocalImgData'] // 必填,需要使用的 JS 接口列表
		});

		let res = await wxChooseImages(count)
		var localIds = res.localIds;

		let paths = []
		for (let i = 0; i < localIds.length; i++) {
			let f = await wxGetLocalImgData(localIds[i])

			var localData = f

			let files = parseBlob(localData)

			var user_domain = url.url_fixed
			uni.showLoading({
				title: '上传中',
				mask: true
			});
			let data = await uni.uploadFile({
				url: user_domain + url.upload, //仅为示例,非真实的接口地址
				filePath: files,
				name: 'iFile'
			});

			let result = JSON.parse(data[1]['data'])
			if (data && result['code'] == 1) {
				let fileData = result['data'][0]
				paths.push({
					file_id: fileData['file_id'],
					file_path: fileData['file_path']
				})
			}
			
			uni.hideLoading();

		}

		return paths

	} catch (e) {
		//TODO handle the exception
		uni.showToast({
			title: "失败",
		});
	}


}

async function wxChooseImages(count=3) {

	return new Promise((resolve, reject) => {
		wx.chooseImage({
			count: count, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
			sourceType: ['album', 'camera'],
			success: function(res) {
				resolve(res)
			}
		});
	});

}

async function wxGetLocalImgData(localIds) {

	return new Promise((resolve, reject) => {
		wx.getLocalImgData({
			localId: localIds,
			success: function(res) {
				
				let imageBase64 = "";
				const localData = res.localData;
				if (localData.indexOf("data:image") == 0) {
				  //苹果的直接赋值,默认生成'data:image/jpeg;base64,'的头部拼接
				  imageBase64 = localData;
				} else {
				  //此处是安卓中的唯一得坑!在拼接前需要对localData进行换行符的全局替换
				  //此时一个正常的base64图片路径就完美生成赋值到img的src中了
				  imageBase64 =
					"data:image/jpeg;base64," +
					localData.replace(/\n/g, "");
				}
				
				resolve(imageBase64)
				
			}
		});
	});

}

你可能感兴趣的:(uni-app,微信,javascript)