<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
获得JSSDK 接口列表
['chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData']
function chooseImage(callback) {
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
wxBaseImage(res.localIds[0], callback);
},
cancel: err => {
callback(err)
}
});
}
function wxBaseImage(localIds, callback) {
// 在开发者工具调试时,需要取消注释这一段,否则无法获得图片
// wx.getLocalImgData({
// localId: localIds, // 图片的localID
// success: res => {
// callback(res);
// },
// });
// return;
wx.uploadImage({
localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function(res) {
var serverId = res.serverId; // 返回图片的服务器端ID
wx.downloadImage({
serverId: serverId, // 需要下载的图片的服务器端ID,由uploadImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function(res) {
wx.getLocalImgData({
localId: res.localId, // 图片的localID
success: function(res) {
// res.localData是图片的base64数据,可以用img标签显示
callback(res);
},
});
},
});
},
});
}
// 将base64转换为blob
function dataURLtoBlob(dataurl) {
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 Blob([u8arr], { type: mime });
}
// 将blob转换为file
function blobToFile (theBlob, fileName) {
let options = {
lastModifiedDate: new Date(),
lastModified: new Date().getTime(),
type: 'image/png',
uid: getUuid(),
webkitRelativePath: '',
};
// File()前两个参数是必填参数,options是选填参数
return new window.File([theBlob], fileName, options);
}
function getUuid() {
var s = [];
var hexDigits = '0123456789abcdef';
for (var i = 0; i < 36; i++)
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = '-';
return s.join('');
}
调用示例
$(".敲击事件").click(e => {
chooseImage(res => {
// 公众号返回IOS与安卓不同,安卓会缺少BASE64头部。在此判断补全
let baseImage = res.localData;
if (baseImage.indexOf('data:image') !== 0)
baseImage = 'data:image/jpeg;base64,' + baseImage;
let formData = new FormData();
formData.append("file", blobToFile(dataURLtoBlob(baseImage), "cat.png"));
formData.append("uid", uid);
$.ajax({
url: "你的上传地址",
type: "POST",
dataType: 'json',
cache: false,
processData: false,
contentType: false,
data: formData,
success: res => {
alert("上传成功");
},
fail: err => {
alert("上传失败");
}
})
})
})