WeChat web development (6)--image interface

1. Background

This article implements the following image-related interfaces, including taking pictures, previewing, uploading, and downloading pictures.

2. Code writing

<html>
<head>
<meta charset="utf-8">
<style>
* {
      
      
	font-size: 1.5em;
}
</style>
</head>
<body>
	<input type="button" value="拍照" onclick="imageTest('chooseImage')"> |
	<input type="button" value="预览" onclick="imageTest('previewImage')"> |
	<input type="button" value="上传" onclick="imageTest('uploadImage')"> |
	<input type="button" value="下载" onclick="imageTest('downloadImage')"> |

	<script src="http://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
	<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
	<script>
		var apiList = [ 'checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage' ];
		$(function() {
      
      
			// 向后端请求配置信息
			$.ajax({
      
      
				type : "GET",
				url : "/wx-server/wxJsapiSignature",
				data : {
      
      
					url : location.href.split('#')[0]
				},
				dataType : "json",
				success : function(res) {
      
      
					configInfo(res);
				}
			});
		});

		// 通过wx.config注入配置信息
		function configInfo(res) {
      
      
			wx.config({
      
      
				debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				appId : res.appId, // 必填,公众号的唯一标识
				timestamp : res.timestamp, // 必填,生成签名的时间戳
				nonceStr : res.nonceStr, // 必填,生成签名的随机串
				signature : res.signature,// 必填,签名
				jsApiList : apiList
			// 必填,需要使用的JS接口列表
			});
			// 处理成功后回调
			wx.ready(function() {
      
      
				console.log("处理成功:");
				wx.checkJsApi({
      
      
					jsApiList : apiList,
					success : function(checkRes) {
      
      
						console.log("checkRes:", checkRes);
					}
				});
			});
			// 处理失败后回调
			wx.error(function(err) {
      
      
				console.log("处理失败:", err);
			});
		}

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

3. Debug

The above code example implements the camera interface. We click the camera to test as follows:
insert image description here

4. Summary

Other interfaces can be implemented by referring to the official documentation.

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/122680019