公众号开发个人笔记:图片上传、预览、删除(仅作个人备忘)
程序员文章站
2024-01-24 15:37:28
...
公众号SDK链接
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#18
图片上传+预览
html
<div class="machine-content">
<img src="{php echo EWEI_SHOPV2_LOCAL}static/clothing/img/big_add.png" id="up" data-id='1'>
</div>
javascript
<script>
let _images = {
localIds: [],
serverId: []
};
$(".machine-content").on('click','#up', function() {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
_images.localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
localIds = _images.localIds
// alert('已选择' + res.localIds.length + '张图片')
let images = [];
$.each(localIds, function(i) {
wxgetLocalImgData(localIds[i], 'filename');
// wxuploadData(localIds[0].toString())
console.log('当前id',$(this).attr("data-id"))
});
},
fail: function(res) {
alert(JSON.stringify(res));
}
});
})
function wxgetLocalImgData(localIds, filename) {
wx.getLocalImgData({
localId: localIds, // 图片的localID
success: function(res) {
var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
if (localData.indexOf('data:image') != 0) {
localData = 'data:image/jpeg;base64,' + localData
}
var obj = dataURLtoFile2(localData, filename); // base64转图片
var product_photos = new FormData();
product_photos.append('file', obj, filename);
product_photos.append('file', filename);
$.ajax({
url: "{php echo mobileUrl('util/dupload')}",
type: "POST",
processData: false,
contentType: false,
data: product_photos,
success: function(data) {
var r = JSON.parse(data);
console.log('数据',r.url)
$("#up").attr('src',r.url);
}
});
},
fail: function(res) {
alert(Error);
}
});
}
// base64转图片
function dataURLtoFile2(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);
}
let f = new Blob([u8arr], {type:mime});
return f;
}
// 预览
$(".q-imagesadd").on('click','.q-uploadimg2', function() {
var previewimgurls =$(this).attr('data-id')
// console.log(previewimgurls)
wx.previewImage({
current: previewimgurls, // 当前显示图片的http链接
urls: [previewimgurls] // 需要预览的图片http链接列表
});
});
// 删除
$(".q-imagesadd").on('click','.delimg', function() {
$(this).parent().remove()
});
</script>