微信公众号开发之商户注册功能-拍照、上传图片(一)

微信公众号中开发一个商户注册功能,没有难点,只是页面排版、微信的一些控件(扫码、上传图片)不熟悉可能会花一点时间。

商户注册功能分两页:第一页填写手机号,获取验证码,输入验证码,输入密码和确认密码,点击下一步,然后填写商户名称,上传商户营业执照和门店照片,扫描我们给商户的收款二维码用来绑定商户号,点击确定保存即商户注册成功。

先说下上传图片功能,刚开始直接做的是用type是file的input来选择手机图片。

var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
    // 1024KB,也就是 1MB
    var maxSize = 1024 * 1024;
    // 图片最大宽度
    var maxWidth = 300;
    // 最大上传图片数量
    var maxCount = 2;
    $('.js_file').on('change', function(event) {
        var files = event.target.files;

        // 如果没有选中文件,直接返回
        if (files.length === 0) {
            return;
        }

        for (var i = 0, len = files.length; i < len; i++) {
            var file = files[i];
            var reader = new FileReader();

            // 如果类型不在允许的类型范围内
            if (allowTypes.indexOf(file.type) === -1) {
                $.weui.alert({
                    text: '该类型不允许上传'
                });
                continue;
            }

            if (file.size > maxSize) {
                $.weui.alert({
                    text: '图片太大,不允许上传'
                });
                continue;
            }

            if ($('.weui_uploader_file').length >= maxCount) {
                $.weui.alert({
                    text: '最多只能上传' + maxCount + '张图片'
                });
                return;
            }

            reader.onload = function(e) {
                var img = new Image();
                img.onload = function() {
                    // 不要超出最大宽度
                    var w = Math.min(maxWidth, img.width);
                    // 高度按比例计算
                    var h = img.height * (w / img.width);
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    // 设置 canvas 的宽度和高度
                    canvas.width = w;
                    canvas.height = h;
                    ctx.drawImage(img, 0, 0, w, h);
                    var base64 = canvas.toDataURL('image/png');

                    // 插入到预览区
                    var $preview = $('<li class="weui_uploader_file weui_uploader_status" style="background-image:url(' + base64 + ')"><div class="weui_uploader_status_content">0%</div></li>');
                    // var $preview = $('<li class="weui_uploader_file weui_uploader_status" style="background-image:url(' + base64 + ')"></li>');
                    $('.weui_uploader_files').append($preview);
                    var num = $('.weui_uploader_file').length;
                    $('.js_counter').text(num + '/' + maxCount);

                    // 然后假装在上传,可以post base64格式,也可以构造blob对象上传,也可以用微信JSSDK上传
                    var progress = 0;
                    function uploading() {
                        $preview.find('.weui_uploader_status_content').text(++progress + '%');
                        if (progress < 100) {
                            setTimeout(uploading, 10);
                        } else {
                            // 如果是失败,塞一个失败图标
                            //$preview.find('.weui_uploader_status_content').html('<i class="weui_icon_warn"></i>');
                            $preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();
                        }
                    }
                    setTimeout(uploading, 10);
                };
                img.src = e.target.result;

                if($("#licenceImg").val() == ''){
                    $("#licenceImg").val(img.src);
                }else {
                    $("#storeImg").val(img.src);
                }


                //encodeURIComponent处理数据,否则后台接收到的数据会不一致
                // $.post('/merchant/register/uploadlicence', 'fileStr=' + encodeURIComponent(img.src),
                //     function (res) {
                //         if(res.code == 1){
                //             $.toast(res.message, 'text');
                //             // popupsForSkip('发起提现成功', '/merchant/personal');
                //         }else {
                //             fail(res.message);
                //         }
                //     }, 'json');

            };
            reader.readAsDataURL(file);
        }
    });

这种方式上传图片,是选择图片后,会获得图片的base64数据,然后在后台将数据转为图片并保存到服务器上。而且ajax提交数据的时候对数据还要用encodeURIComponent处理一下,否则在后台获取到的数据可能会出现错误导致转图片时失败。

这种方式完成上传图片后,被无情的驳回。理由是对于用户体验不友好,假如说用户来注册商户了,当他到了上传图片这一步的时候发现自己还没有拍照片,岂不是要返回拍个照片后再来上传。

于是改,让商户既能拍照也能选择照片。微信专门的接口来做这件事。
1、首先这几个值要有:

var timestamp = $("#timestamp").val();//时间戳
    var nonceStr = $("#nonceStr").val();//随机串
    var signature = $("#signature").val();//签名
    var appId = $("#appId").val();//公众号appid

wx.config({
        debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId : appId, // 必填,公众号的唯一标识
        timestamp : timestamp, // 必填,生成签名的时间戳
        nonceStr : nonceStr, // 必填,生成签名的随机串
        signature : signature,// 必填,签名,见附录1
        jsApiList : [ 'scanQRCode','chooseImage','uploadImage' ]
    });

其中jsApList是调用功能所需的权限值。这三个分别是:扫码、选择图片、上传图片

按钮点击事件:

wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function (res) {
                $("#uploadLicence").remove();
                var localIds = res.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片

                syncUpload(localIds,"previewLicence");
            }
        });

上传到微信服务器,并返回服务器端ID:

//上传图片到微信服务器,并返回服务器端ID
    var syncUpload = function (localIds,ulName) {
        wx.uploadImage({
            localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1,显示进度提示
            success: function (res) {
                var serverId = res.serverId; // 返回图片的服务器端ID
                uploadServerId(serverId,ulName);
            }
        });
    };

上传图片到我们的服务器,并返回图片路径,js组装后显示在页面:

 //异步上传图片id到服务器,服务器返回真正的图片地址,js组装后显示在页面上
    var uploadServerId = function (serverId,ulName) {
        $.post('/merchant/register/uploadimg', 'mediaId=' + serverId,
            function (res) {
                if(res.code == 1){
                    $.toast(res.message, 'text');
                    var url = res.data;
                    var licenceImg = "<img style='width:60px;height: 60px;' class='weui_uploader_file' src='"+url+"'/>";
                    $("#"+ulName).append(licenceImg);
                    if(ulName == 'previewLicence'){
                        $("#licenceImg").val(url);
                        $("#js_counter_licence").html("(1/1)");
                        $("#licencediv").remove();
                    }else {
                        $("#storeImg").val(url);
                        $("#js_counter_store").html("(1/1)");
                        $("#uploadStoreImg").hide();
                        $("#storediv").remove();
                    }
                }else {
                    fail(res.message);
                }
            }, 'json');
    };

后台得到mediaId去微信服务器拿到图片,然后写到本地服务器上:

@PostMapping("/uploadimg")
    public @ResponseBody WebResponse uploadimg(String mediaId) throws Exception{
        String tokenMsg = WxTokeanUtil.getToken();
        String rootPath = new FileOperation().getRootPath();
        File shopImage = new File(rootPath+File.separator+"assets/shopImage");
        if(!shopImage.exists() || !shopImage.isDirectory()){
            shopImage.mkdirs();
        }
        UUID uuid = UUID.randomUUID();
        String imageName = uuid.toString();
        String imageType = ".jpg";
        InputStream inputStream = getInputStream(tokenMsg,mediaId);
        byte[] data = new byte[10240];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
                fileOutputStream = new FileOutputStream(rootPath+File.separator+"assets/shopImage"+File.separator+imageName+imageType);
                while ((len = inputStream.read(data))!= -1){
                    fileOutputStream.write(data, 0, len);
                }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return WebResponse.getWebResponse(true,"上传成功","/assets/shopImage"+File.separator+imageName+imageType);
    }

public static InputStream getInputStream(String accessToken, String mediaId) {
        InputStream is = null;
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="
                + accessToken + "&media_id=" + mediaId;
        try {
            URL urlGet = new URL(url);
            HttpsURLConnection http = (HttpsURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
//            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
//            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            // 获取文件转化为byte流
            is = http.getInputStream();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;

    }

到此图片的拍照、上传功能实现。

猜你喜欢

转载自blog.csdn.net/kanglovejava/article/details/79305095