zoukankan      html  css  js  c++  java
  • 微信公众号开发h5,上传图片

    1.获取微信开放功能的基础参数配置,类似分享功能,定位功能也都需要获取改参数,

    • 注意:需要配置授权域名链接
    • 需要配置ip白名单
        <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
            wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                    appId: '{$weixin.appId}', // 必填,公众号的唯一标识
                    timestamp: '{$weixin.timestamp}', // 必填,生成签名的时间戳
                    nonceStr: '{$weixin.nonceStr}', // 必填,生成签名的随机串
                    signature: '{$weixin.signature}', // 必填,签名,见附录1
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        'openLocation',
                        'chooseWXPay',
                        'chooseImage',                  // 这里需有选择图片,上传图片的功能,
                        'uploadImage'
                    ]
                });
                wx.ready(function () {
    
                    // wx.onMenuShareAppMessage({
                    //     title: '标题', // 分享标题
                    //     desc: `描述`, // 分享描述
                    //     link: `http://*******/wx.php`, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    //     imgUrl: 'https://cdn.caomall.net/15606006301896208141.jpg', // 分享图标
                    //     success: function () {
                    //         // 用户确认分享后执行的回调函数
                    //     },
                    //     cancel: function () {
                    //         // 用户取消分享后执行的回调函数
                    //     }
                    // });
            
                    // wx.onMenuShareTimeline({
                    //     title: '标题', // 分享标题
                    //     desc: `描述`, // 分享描述
                    //     link: `http://*******/wx.php`, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    //     imgUrl: 'https://cdn.caomall.net/15606006301896208141.jpg', // 分享图标
                    //     success: function () {
                    //         // 用户确认分享后执行的回调函数
                    //     },
                    //     cancel: function () {
                    //         // 用户取消分享后执行的回调函数
                    //     }
                    // });      
                    
                });
          </script>  
    
    

    选择图片,上传图片

    • 注意:微信开发工具不可真正上传,但流程都中转参数都对的,仔细观察会发现上传的severId是不变的----这个就是微信的坑了!!!!!
    • 必须用手机上传,没张图片上传可能需要些时间;
    var pics = [];
    $('#add_btn_1').on('click',function(){
        let max_count = 3;
        if(pics.length >= max_count){
            return alert('最多3张');
        }
    
        //alert('sss');
        wx.chooseImage({
            count: max_count - pics.length, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function (res) {
                console.log(res);
                var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片                
                
                new Promise(function(resolve,reject){
                    for(var i = 0;i< localIds.length;i++){
                        wx.uploadImage({
                            localId: localIds[i], // 需要上传的图片的本地ID,由chooseImage接口获得
                            isShowProgressTips: 1, // 默认为1,显示进度提示
                            complete: function (res) {
                                console.log('-----');
                                console.log(res);
                                var serverId = res.serverId; // 返回图片的服务器端ID
            
                                $.ajax({
                                    type      : 'POST',
                                    dataType  : 'json',
                                    url       : '/api.php/Upload/uploadServerId',
                                    data      : { serverId },
                                    success   : function(data){
                                        if(!data.errno){
                                            console.log(data);                           
                                            pics.push(data.data);                       
                                        } else {
                                            return alert(data.errdesc);
                                        }
                                    },error   : function(){
                                        alert('网络错误');
                                    }
                                });  
            
                            }
                        });
                    }
    
                    setTimeout(function(){
                        resolve(pics);
                    },1500 * localIds.length);      // 一张上传时间比较长....2s
    
                }).then(function(pics){
                    console.log('then---执行');
                    let ejs_data = [];
                    ejs_data.data = pics;
                    console.log('ggggggggggggggggggggg');
                    console.log(ejs_data);
                    var ec_canvs = new EJS({ element: "ejs_pics_id"}).render(ejs_data);         // 这里用ejs,实现上传多图样式拼接;
                    $("#imageWrap").html(ec_canvs);                
                })
            }
        });   
          
    });
    

    上传media_id,生成图片,上传到我们自己服务器功能

        /**
         * 微信公众号 上传图片
         */
        public function uploadServerId() {
            if (!$serverId = $_POST['serverId']) {
                $this->json->E('缺少serverId',10001);
            }
    
    
    
            $url = C('PROXY_HOST') . 'Media/getMediaImg';
            $params = [
                'media_id' => $serverId
            ];
    
            $cdn_result = Http::newDoPost($url,$params);
            $cdn_result = json_decode($cdn_result, true);
            setlog($cdn_result,[],'','up.log');
    
            if ((int)$cdn_result['code'] === 1) {
                $this->json->S($cdn_result['data']);
            } else {
                $this->json->E('服务器繁忙');
            }
        }
    
    
    <?php
    namespace ProxyAction;
    
    use VendorFuncFunc;
    use VendorFuncHttp;
    use VendorQiniuQiniu;
    
    class MediaAction extends CommonAction
    {
        // 获取媒体数据
        //http://file.api.weixin.qq.com/cgi-bin/media/upload
        const API_MEDIA_GET = 'http://file.api.weixin.qq.com/cgi-bin/media/get';
    
        public function getMediaImg() {
            $access_token = $this->_get_access_token();
            // 获取参数
            $media_id = $_POST['media_id'];
            $params = [
                'access_token'  => $access_token,
                'media_id'      => $media_id,
                'type'          => 'thumb'                  // 这里用image,可能太大会上传不了;
            ];
            $result = Http::newDoGet(self::API_MEDIA_GET, $params);
            $decode_res = json_decode($result,true);
            if($decode_res['errcode'] != 0){
                $this->ajaxReturn($this->jsonError(10021, $decode_res['errmsg']));
            }
    
            // 存入cdn
            $cdn_result = $this->uploadCdn($result);            // 上传cdn, 具体功能函数省略...
            //setlog($cdn_result,[$result],'media_result','proxy_error_2.log');
            setlog($cdn_result,[],'media_result','proxy_error_222.log');
    
            if ((int)$cdn_result['errno'] === 0) {
                $this->ajaxReturn($this->jsonSuccess(1, '成功', $cdn_result['save_name']));
            } else {
                $this->ajaxReturn($this->jsonError(10001, '服务器繁忙'));
            }
        }
    
    }
    ?>
    
    

    • 参考博客
    https://www.jb51.net/article/161349.htm
    https://www.cnblogs.com/fanshuyao/p/6227130.html
    https://blog.csdn.net/zzwwjjdj1/article/details/52354763
    https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_temporary_materials.html
    
    • 参考微信开放手册
    https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#19
    https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E5%9F%BA%E7%A1%80%E6%94%AF%E6%8C%81&form=%E5%A4%9A%E5%AA%92%E4%BD%93%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E6%8E%A5%E5%8F%A3%20/media/upload
    
  • 相关阅读:
    利用for循环 修改精灵图背景位置
    添加列表项 避免浏览器反复渲染 Fragment
    向元素添加属性名和属性值
    分割文本节点
    查询、回显 基本功能
    获取注释
    合并文本节点
    Node(节点)的4个操作方法
    setTimeout与setInterval
    javascript循环
  • 原文地址:https://www.cnblogs.com/pansidong/p/13330429.html
Copyright © 2011-2022 走看看