前端实现微信公众号图片上传预览jssdk

最近做了公众号的项目,需要用jssdk,研究了一段时间也走了一些弯路,现在做一些记录

1.首先引入 <script src = "http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

2.配置jssdk

//配置jssdk

            var pageUrl = {

                url:encodeURIComponent(location.href.split('#')[0])  //此处必须用#的方式处理地址

            };

            var work = JSON.stringify(pageUrl);

        

            var thats = this;

            // 配置jssdk ;

            $.ajax({

                url:"http://**********************/getWeChat.jsp",  //后台提供的地址,用来返回字段

                // dataType: "json",

                type:"post",

                // data:pageUrl,

                data:{

                    pageUrl:work

                },

                success:function(data){

                    console.log( data);

                    // return ;

                    var obj = JSON.parse(data);

 

                    console.log(obj.signature,obj.nonceStr,obj.timestamp);

                    wx.config({

                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

                        appId: 'wxca6121212fff29539', // 必填,公众号的唯一标识(liu)wxca6f1f5b29129539

                        timestamp: obj.timestamp, // 必填,生成签名的时间戳

                        nonceStr: obj.nonceStr, // 必填,生成签名的随机串

                        signature: obj.signature,// 必填,签名

                        jsApiList: ['chooseImage','uploadImage'] // 必填,需要使用的JS接口列表

                    });

                    // return ;

                    wx.ready(function(){

                        // alert("success");

                        console.log("success111");

                        // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。

                        

                    });

                    wx.error(function(res){

                        alert("error");

                        console.log(res)

                        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。

                    });

                },

                error:function(err){

                    alert("error");

                    console.log(err);

                    console.log(err.response)

                    console.log("error")

                }

            })

 

3.选图

wx.chooseImage({

                count: 9, // 默认9

                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有

                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

                success: function (res) {

                    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片

                    var xt = navigator.userAgent;

                    if(xt.indexOf("OS") > -1){

                        alert("ios");

                        // ios苹果转base64显示

                        for(let j=0;j<localIds.length;j++){

                            wx.getLocalImgData({

                                localId: localIds[j], // 图片的localID

                                success: function (res) {

                                    localIds = res.localData; // localData是图片的base64数据,可以用img标签显示

                                    // alert(JSON.stringify(localIds))

                                    alert(localIds);

                                    var html="",ht="",ml="";

                                    if(localIds==1){

                                        ht="<li style = 'position:relative;width: 32%;margin-bottom: .2rem;margin-right:1%;height: 120px;-webkit-box-flex: 0;flex: 0 0 auto;'><img src='"+res.localData+"' alt=''><div style = 'width:20px;height:20px;background:rgba(255,0,0,0.5);border-radius:50%;position:absolute;top:0;right:0;text-align:center;line-height:20px;' class = 'delImage'>x</div></li>"

                                    }else {

                                        ml+="<li style = 'position:relative;width: 32%;margin-bottom: .2rem;margin-right:1%;height: 120px;-webkit-box-flex: 0;flex: 0 0 auto;'><img src='"+res.localData+"' alt=''><div style = 'width:20px;height:20px;background:rgba(255,0,0,0.5);border-radius:50%;position:absolute;top:0;right:0;text-align:center;line-height:20px;' class = 'delImage'>x</div></li>"

                                    }

                                    html+=ht+ml;

                                    alert(html);

                                    $('.xuantuBox').append(html);

                                    funcReadImgInfo();//点击查看大图  图片预览功能

                                    // alert(JSON.stringify(result1))

                                },

                                fail: function (res) {

                                    // alert("请联系开发人员")

                                    alert(JSON.stringify(res))

                                }

                            });

                        }

                    }else {

                        // alert("安卓");

                        $.each(localIds,function(i,n){

                            $(".xuantuBox").append("<li style = 'position:relative;width: 32%;margin-bottom: .2rem;margin-right:1%;height: 120px;-webkit-box-flex: 0;flex: 0 0 auto;'><img style = 'width:100%;height:100%;' src = '"+n+"'><div style = 'width:20px;height:20px;background:rgba(255,0,0,0.5);border-radius:50%;position:absolute;top:0;right:0;text-align:center;line-height:20px;' class = 'delImage'>x</div></li>");

                            // $(".xuantuBox").append("<li style = 'position:relative;width: 32%;margin-bottom: .2rem;height: 120px;-webkit-box-flex: 0;flex: 0 0 auto;'><img style = 'width:100%;height:100%;' src = '"+n+"'><div style = 'width:40px;height:40px;background:red;position:absolute;top:0;right:0;text-align:center;line-height:40px;' class = 'delImage'>x</div></li>");

                            

                        });

                        funcReadImgInfo()//图片预览

                    }

 

                    //点击查看大图

                    function funcReadImgInfo() {

                        

                        var imgs = [];

                        var imgObj = $(".xuantuBox img");//这里改成相应的对象

                        for (var i = 0; i < imgObj.length; i++) {

                            imgs.push(imgObj.eq(i).attr('src'));

                            imgObj.eq(i).click(function () {

                                var nowImgurl = $(this).attr('src');

                                //alert(nowImgurl)

                            // alert(JSON.stringify(result1))

                                WeixinJSBridge.invoke("imagePreview", {

                                    "urls": imgs,

                                    "current": nowImgurl

                                });

                            });

                        }

                    }

                }

            });

4.上传,多图上传

//上传图片

                var alllist = []; //给微信服务器上传

                var uploadBack = '';//要给后台的东西,

                if($('.xuantuBox img').length>0){

                    console.log("youtu");

                    // 获取上传图片的id

                    

                    $.each($('.xuantuBox img'),function(i,m){

                        alllist.push(m.getAttribute("src"));

                        

                    })

                    syncUpload(alllist);

                    function syncUpload(localIds){

                        var localIdlist = localIds.pop();

                        wx.uploadImage({

                            localId: localIdlist.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得

                            isShowProgressTips: 1, // 默认为1,显示进度提示

                            success: function (res) {

                                var serverId = res.serverId; // 返回图片的服务器端ID,这个serverid是前端吧选择的图片localids上传给微信服务器,微信服务器返回给前端的serverid,前端吧这个给了后台即可

                                uploadBack += '["'+serverId+'"],';

                                // alert(uploadBack);

                                if(localIds.length > 0){

                                    

                                    window.setTimeout(function(){

                                        syncUpload(localIds);

                                    },100);

                                }else{

                                    window.setTimeout(function(){

                                        // downloadImage(0);

                                    },100);

                                }

                                

 

                            },

                            fail:function(res){

                                alert("上传错误");

                            }

                        });

                    }

                }

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值