1.wx.config配置
2.wx.chooseImage选择图片
3.wx.getLocalImgData获取图片base64编码
4.base64转成file
5.利用form上传file
示例文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微信接口测试</title>
</head>
<body style="text-align: center;">
<button id="chooseImg" style="width:30%;height:100px;margin-top: 45%;font-size: 18px;">选择图片</button>
<br>
<div id="imgDiv"></div>
<br>
<form name="imgForm" style="display:none;"></form>
<button οnclick="sendBlessing()" style="width:30%;height:100px;margin-top: 45%;font-size: 18px;">发送祝福</button>
</body>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
initConf();
// 微信配置
function initConf() {
var url = location.href.split("#")[0];
$.ajax({
type: "GET",
url: "https://mos.i847.cn/api/m/wechat/share/config",
data: {"url": encodeURIComponent(url)},
dataType: "json",
success: function (data) {
data.jsApiList = ['chooseImage', 'uploadImage', 'getLocalImgData', 'downloadImage', 'previewImage', 'getLocalImgData'];
wx.config(data);
wx.ready(function () {
$("#chooseImg").click(function () {
chooseImg();
});
});
wx.error(function (res) {
});
}
});
}
// 选择图片并上传临时文件
var localIds = [];
var img = [];
function chooseImg() {
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
$("#imgDiv").empty();
localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
img = [];
$.each(localIds, function (index, item) {
// 获取base64
wx.getLocalImgData({
localId: item, // 图片的localID
success: function (res) {
var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
if (localData.indexOf('data:image') != 0) {
localData = 'data:image/jpeg;base64,' + localData
}
var form = document.imgForm;
var formData = new FormData(form);
var fileName = new Date().getTime() + ".jpeg";
formData.append("file", dataURLtoFile(localData, fileName));
$.ajax({
type: "POST",
url: "https://mos.i847.cn/api/annual/attachment?openId=orfcH59MbD88bA879pNTFR_aMxCs",
data: formData,
dataType: "json",
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (data) {
img.push(data);
$("#imgDiv").append('<img style="width:100px;height:100px;" src="' + data.url + '"/>');
}
});
}
});
});
}
});
}
//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type: mime});
}
</script>
</html>