微信js sdk上傳多張圖片


微信js sdk上傳多張圖片,微信上傳多張圖片

該案例已tp3.2商城為例

直接上代碼:

php代碼:

 public function ind(){
        $appid="11111111111111111111";
        $secret="11111111111111111111";
        $token = S('access_token');
        if (!$token) {
            $res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=11111111111111&secret=11111111111111111111111111");
            $res = json_decode($res, true);
            $token = $res['access_token'];
            // 注意:這里需要將獲取到的token緩存起來(或寫到數據庫中)
            // 不能頻繁的訪問https://api.weixin.qq.com/cgi-bin/token,每日有次數限制
            // 通過此接口返回的token的有效期目前為2小時。令牌失效后,JS-SDK也就不能用了。
            // 因此,這里將token值緩存1小時,比2小時小。緩存失效后,再從接口獲取新的token,這樣
            // 就可以避免token失效。
            // S()是ThinkPhp的緩存函數,如果使用的是不ThinkPhp框架,可以使用你的緩存函數,或使用數據庫來保存。
            S('access_token', $token, 3600);
        }
        $ticket = S('wx_ticket');
        if(!$ticket) {
            $tokinfo = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$token&type=jsapi");
            $tokinfo = json_decode($tokinfo, true);
            $ticket=$tokinfo['ticket'];
            S('wx_ticket', $ticket, 3600);
        }
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        if($ticket){
            $timestamp = time();
            $wxnonceStr = "abcdefghijklmnopqrstuvw";
            $wxticket = $ticket;
            $wxOri = "jsapi_ticket=$wxticket&noncestr=$wxnonceStr&timestamp=$timestamp&url=$url";
            $wxSha1 = sha1($wxOri);
            $this->assign("token",$token);
            $this->assign("timestamp",$timestamp);
            $this->assign("wxnonceStr",$wxnonceStr);
            $this->assign("wxshal",$wxSha1);
        }
    }

 

模板中的js代碼:

  // 微信配置
        var token="{$token}";
        var timestamp="{$timestamp}";
        var wxnonceStr = "{$wxnonceStr}";
        var wxshal = "{$wxshal}";
        wx.config({
            debug: false,
            appId: "wx978a1c1edb5fea34",
            timestamp: "{$timestamp}",
            nonceStr: "{$wxnonceStr}",
            signature: "{$wxshal}",
            jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline','chooseImage','previewImage','uploadImage','downloadImage'] // 功能列表,我們要使用JS-SDK的什么功能
        });
        var serverids=[];
        var leng=0;
        var syncUpload = function(localIds){
            myApp.hidePreloader();
            myApp.showPreloader();
            var localId = localIds.pop();
            wx.uploadImage({
                localId: localId,
                isShowProgressTips:0,
                success: function (res) {
                    var serverId = res.serverId; // 返回圖片的服務器端ID
                    serverids.push(serverId);
                    //其他對serverId做處理的代碼
                    if(localIds.length > 0){
                        syncUpload(localIds);
                    }
                    if(leng==serverids.length){
                        var json = {};
                        for(var i=0;i<serverids.length;i++)
                        {
                            json[i]=serverids[i];
                        }
                        var serids=JSON.stringify(json);
                        $.ajax({
                            type : "post",
                            url : "/H5/index/downloadMedia",
                            data : {mediaid:serids} ,
                            dataType:"json",
                            async : false,
                            success : function(response){
                                myApp.hidePreloader();
                                $.each(response.image,function (k,v) {
                                    var contentUl = SetImgBox(v);
                                    $(".img_box").append(contentUl);
                                })
                                myApp.hidePreloader();
                                alert("上傳成功!");
                                //alert(response.image[0])
                                //$(".ago").attr("src",response.image[0])
                            }
                        });
                    }
                }
            });
        };
        $(function () {
            wx.ready(function () {
                // 獲取“分享到朋友圈”按鈕點擊狀態及自定義分享內容接口
                $("#contentid").click(function () {
                    var ileng=$("#imglength li").length;
                    var wleng=9+1-ileng;
                    var that = $(this);
                    wx.chooseImage({
                        count: wleng, // 默認9
                        sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
                        sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
                        success: function (res) {
                            var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作為img標簽的src屬性顯示圖片
                            leng = localIds.length;
                            syncUpload(localIds); //上傳代碼圖片就在此直接調用
                        }
                    });
                })
            })
        })

 

php 服務器接收的代碼:

 public function downloadMedia() {
        $mediaId=$_POST["mediaid"];
        $appid="11111111111111111111";
        $secret="222222222222222222222222222";
        $mediaId = json_decode($mediaId);
        $token = S('access_token');
        $imgs=array();
        if (!$token) {
            $res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=11111111111111111111&secret=11111111111111111111111111111");
            $res = json_decode($res, true);
            $token = $res['access_token'];
            // 注意:這里需要將獲取到的token緩存起來(或寫到數據庫中)
            // 不能頻繁的訪問https://api.weixin.qq.com/cgi-bin/token,每日有次數限制
            // 通過此接口返回的token的有效期目前為2小時。令牌失效后,JS-SDK也就不能用了。
            // 因此,這里將token值緩存1小時,比2小時小。緩存失效后,再從接口獲取新的token,這樣
            // 就可以避免token失效。
            // S()是ThinkPhp的緩存函數,如果使用的是不ThinkPhp框架,可以使用你的緩存函數,或使用數據庫來保存。
            S('access_token', $token, 3600);
        }
        foreach ($mediaId as $key=>$value){
            $nfilename = date('YmdHis').get_rand_str(6);
            $day=date("Y");
            $dam=date("m");
            $updir = './Public/trade/'.$day.'/'.$dam.'/';
            $updir2 = '/Public/trade/'.$day.'/'.$dam.'/';
            if (!is_dir($updir)){
                //第三個參數是“true”表示能創建多級目錄,iconv防止中文目錄亂碼
                $res=mkdir(iconv("UTF-8", "GBK", $updir),0777,true);
                if (!$res){
                    $this->error = "目錄 $updir 創建失敗";
                    return false;
//                $this->output_error("目錄 $updir 創建失敗");
                }
            }
            $med=$value;
            $content = file_get_contents("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$token&media_id=$med");
            $filename = "$updir/$nfilename.jpg";
            $file2="$updir2/$nfilename.jpg";
            file_put_contents($filename, $content);
            array_push($imgs,$file2);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM