手机端调用微信js-sdk图片上传与预览

ぐ巨炮叔叔 提交于 2020-03-01 21:31:33
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>    function weixinupimg(){        $.ajax({            type: "POST",            url: API_URL+"ass/user/js-sign",            data: {                url: location.href,            },            dataType: "json",            async: false,            success: function (d) {                wx.config({                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。                    appId:d.data.appId,// 必填,公众号的唯一标识                    timestamp:d.data.timestamp, // 必填,生成签名的时间戳                    nonceStr:d.data.nonceStr , // 必填,生成签名的随机串                    signature: d.data.signature,// 必填,签名                    jsApiList: [ 'chooseImage', 'uploadImage',] // 必填,需要使用的JS接口列表                });                wx.ready(function () {                    $(".thubimclick1").on('click',function () {                        var ziduan = $(this).data('name');                        wx.chooseImage({ //调取摄像头和相册                            count: 1, // 最多可以选择的图片张数,默认9                            sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有                            sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有                            success: function (res) {                                var localIds = res.localIds; // 返回选定照片的本地ID列表(手机上操作就是手机端的ID列表,是一个数组),localId可以作为img标签的src属性显示图片                                console.log(res)                                wx.uploadImage({ //上传到微信服务器                                    localId: localIds[0].toString(), // 需要上传的图片的本地ID,由chooseImage接口获得                                    isShowProgressTips: 1, // 默认为1,显示进度提示                                    success: function (result) {                                        var serverId = result.serverId; // 返回图片的服务器端ID 图片下载到本地服务,此处需要后台去处理了,                                        // console.log(res)                                        // 可以将serverId传给后台,用于存放在自己服务器上                                        // if (serverId) {                                        //     // $(".thumbimg").css("display","inline-block");                                        //     // $(".thumbimg").find("img").attr("src", localIds);                                        //     $('input[name = "'+ziduan+'"]').next().css({'display':'inline-block'});                                        //     $('input[name = "'+ziduan+'"]').next().children().attr('src',localIds);//将压缩后的图片显示预览                                        // }                                        // return false;                                        $.ajax({                                            url: API_URL +'ass/wechatupload/wechat-upload?gid=' + getUrlParam('gid') + '&memtype=' + getUrlParam('memtype'),                                            data:{                                                imgserverid:serverId,                                                source_id:getUrlParam('gid'),                                                tablename:getUrlParam('memtype')==22?'ass_company':"ass_individual",//三目运算符                                                //tablename:getUrlParam('memtype')==22?'ass_company':"ass_individual",//三目运算符                                            },                                            type: 'post',                                            success:function(data){                                                if(data.status == 1){                                                    console.log($('input[name = "'+ziduan+'"]'));                                                    // $(this).parent().prev().children('.grad3yulan').attr('src',data.data.img);                                                    $('input[name = "'+ziduan+'"]').next().show();                                                    $('input[name = "'+ziduan+'"]').next().css({'display':'inline-block'});                                                    var bb=$('input[name = "'+ziduan+'"]').next().children().attr('src',data.data.file);//将压缩后的图片显示预览                                                    $('input[name = "'+ziduan+'"]').attr('name');//通过input 获取到name的值,后台需要此参数需要保留                                                    $('input[name = "'+ziduan+'"]').val(data.data.id);                                                }else{                                                    layer.msg(data.msg);                                                }                                            },                                            error:function () {                                                layer.msg('数据有误!');                                            }                                        })                                        // console.log(serverId);                                    }                                });                            },                            fail: function() {},                            complete: function() {}                        });                    })                })            },            error: function (){                alert("发生错误,请咨询公众平台客服");            }        });    }</script>
方法二
<script>
    $.ajax({
        type: "POST",
        url: API_URL+"ass/user/js-sign",
        data: {
            url: location.href,
        },
        dataType: "json",
        async: false,
        success: function (d) {
            wx.config({
                debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId:d.data.appId,// 必填,公众号的唯一标识
                timestamp:d.data.timestamp, // 必填,生成签名的时间戳
                nonceStr:d.data.nonceStr , // 必填,生成签名的随机串
                signature: d.data.signature,// 必填,签名
                jsApiList: [ 'chooseImage', 'uploadImage','downloadImage','previewImage'] // 必填,需要使用的JS接口列表
            });
            wx.ready(function () {
                $(".thubimclick1").click(function () {
                    console.log(85858)
                    var ziduan = $(this).data('name');
                    wx.checkJsApi({
                        jsApiList: [
                            'chooseImage',
                            'previewImage',
                            'uploadImage',
                            'downloadImage'
                        ],
                        success: function (res) {
                            //alert(JSON.stringify(res));
                            //alert(JSON.stringify(res.checkResult.getLocation));
                            if (res.checkResult.getLocation == false) {
                                alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!');
                                return;
                            }else{
                                wxChooseImage();
                            }
                        }
                    });
                })
            });
            var images = {
                localId: [],
                serverId: []
            };
            //拍照或从手机相册中选图接口
            function wxChooseImage() {
                wx.chooseImage({
                    success: function(res) {
                        images.localId = res.localIds;
                        // alert('已选择 ' + res.localIds.length + ' 张图片');
                        if (images.localId.length == 0) {
                            // alert('请先使用 chooseImage 接口选择图片');
                            return;
                        }
                        var i = 0, length = images.localId.length;
                        images.serverId = [];
                        function upload() {
                            //图片上传
                            wx.uploadImage({
                                localId: images.localId[i],
                                success: function(res) {
                                    i++;
                                    images.serverId.push(res.serverId);
                                    //图片上传完成之后,进行图片的下载,图片上传完成之后会返回一个在腾讯服务器的存放的图片的ID--->serverId
                                    wx.downloadImage({
                                        serverId: res.serverId, // 需要下载的图片的服务器端ID,由uploadImage接口获得
                                        isShowProgressTips: 1, // 默认为1,显示进度提示
                                        success: function (res) {
                                            var localId = res.localId; // 返回图片下载后的本地ID
                                            //通过下载的本地的ID获取的图片的base64数据,通过对数据的转换进行图片的保存
                                            wx.getLocalImgData({
                                                localId: localId, // 图片的localID
                                                success: function (res) {
                                                    var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
                                                    //通过ajax来将base64数据转换成图片保存在本地
                                                    $(".thumbimg").css("display","inline-block");
                                                    $(".thumbimg").find("img").attr("src", localData);
                                                }
                                            });
                                        }
                                    });
                                    if (i < length) {
                                        upload();
                                    }
                                },
                                fail: function(res) {
                                    alert(JSON.stringify(res));
                                }
                            });
                        }
                        upload();
                    }
                });
            }
            },
        error: function (){
            alert("发生错误,请咨询公众平台客服");
        }
    });
</script>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!