Call WeChat JS-SDK interface to upload pictures

      Recently, I want to do a questionnaire survey on WeChat. There is a function of uploading pictures. After searching for information for a long time, it is not easy to get it. Finally, I plan to call the uploading picture interface provided by WeChat to realize the function of uploading pictures! The biggest advantage of this function is that it can temporarily store pictures on the WeChat server, reduce the cache of the local server pictures, wait until the final submission, download the pictures from the interface provided by WeChat and save them in the local server!

     WeChat JS-SDK documentation

Overview

WeChat JS-SDK is a web development toolkit based on WeChat provided by WeChat public platform for web developers.

By using WeChat JS-SDK, web developers can use WeChat to efficiently use the capabilities of mobile phone systems such as photography, image selection, voice, location, etc., and can directly use WeChat's unique capabilities such as sharing, scanning, card coupons, and payment. , to provide WeChat users with a better web experience.

This document introduces how to use WeChat JS-SDK and related precautions for web developers.

JSSDK usage steps

Step 1: Bind a domain name

First log in to the WeChat public platform, enter the "Function Settings" of "Official Account Settings" and fill in "JS Interface Security Domain Name".

Note: After logging in, you can view the corresponding interface permissions in the "Developer Center".

Step 2: Import JS files

Introduce the following JS file to the page that needs to call the JS interface (https is supported): http://res.wx.qq.com/open/js/jweixin-1.0.0.js

If you want to use the shake peripheral function, please import http://res.wx.qq.com/open/js/jweixin-1.1.0.js

Remarks: Supports loading using AMD/CMD standard module loading method

Step 3: Inject permission verification configuration through the config interface

All pages that need to use JS-SDK must inject configuration information first, otherwise they cannot be called (the same url only needs to be called once, and the web app of the SPA that changes the url can be called every time the url changes. Currently, the Android WeChat client The new H5 feature of pushState is not supported, so using pushState to implement web app pages will cause the signature to fail. This problem will be fixed in Android 6.2).

wx.config({

    debug: true, // Turn on the debug mode, the return values ​​of all the apis called will be alerted on the client side, if you want to view the incoming parameters, you can open it on the pc side, and the parameter information will be printed out through the log, only on the pc side will print.

    appId: '', // Required, the unique ID of the official account

    timestamp: , // required, the timestamp of the generated signature

    nonceStr: '', // Required, generate a random string for signature

    signature: '',// Required, signature, see Appendix 1

    jsApiList: [] // Required, a list of JS interfaces to be used, see Appendix 2 for a list of all JS interfaces

});

Step 4: Handle successful verification through the ready interface

wx.ready(function(){

    // After the config information is verified, the ready method will be executed. All interface calls must be made after the config interface obtains the result. config is an asynchronous operation on the client side. Therefore, if the relevant interface needs to be called when the page is loaded, the relevant interface must be placed in the ready function to ensure correct execution. For the interface that is called only when the user triggers it, it can be called directly, and does not need to be placed in the ready function.

});

Step 5: Handle failed verification through the error interface

wx.error(function(res){

    // If the verification of config information fails, the error function will be executed. If the signature expires and the verification fails, the specific error information can be viewed in the debug mode of config, or in the returned res parameter. For SPA, the signature can be updated here.

});

Interface call description

All interfaces are called through wx objects (jWeixin objects can also be used), and the parameter is an object. In addition to the parameters that each interface needs to pass, there are also the following general parameters:

1.success: The callback function that is executed when the interface call is successful.

2.fail: The callback function to be executed when the interface call fails.

3.complete: The callback function that is executed when the interface call is completed, whether it succeeds or fails, it will be executed.

4. cancel: The callback function when the user clicks cancel. Only some APIs that have the user cancel operation will be used.

5.trigger: 监听Menu中的按钮点击时触发的方法,该方法仅支持Menu中的相关接口。

备注:不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回。

以上几个函数都带有一个参数,类型为对象,其中除了每个接口本身返回的数据之外,还有一个通用属性errMsg,其值格式如下:

调用成功时:"xxx:ok" ,其中xxx为调用的接口名

用户取消时:"xxx:cancel",其中xxx为调用的接口名

调用失败时:其值为具体错误信息

图像接口

拍照或从手机相册中选图接口

wx.chooseImage({

    count: 1, // 默认9

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

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

    success: function (res) {

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

    }

});

预览图片接口

wx.previewImage({

    current: '', // 当前显示图片的http链接

    urls: [] // 需要预览的图片http链接列表

});

上传图片接口

wx.uploadImage({

    localId: '', // 需要上传的图片的本地ID,由chooseImage接口获得

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

    success: function (res) {

        var serverId = res.serverId; // returns the server-side ID of the image

    }

});

Note: Uploaded pictures are valid for 3 days. You can download pictures to your own server through the WeChat multimedia interface. The serverId obtained here is media_id.

Download image interface

wx.downloadImage({

    serverId: '', // The server ID of the image to be downloaded, obtained from the uploadImage interface

    isShowProgressTips: 1, // The default is 1, showing progress tips

    success: function (res) {

        var localId = res.localId; // Returns the local ID after the image is downloaded

    }

});

According to the interface documentation:

   After the introduction of JS, the authorization verification configuration is performed, and the relevant parameter values ​​are obtained through the Ajax background request :

    $.ajax({
                url: "test.ashx",
                data: {
                    name: "GetWxJsApi",
                    curUrl: url
                },
                type: 'post',
                dataType: "json",
                success: function (data) {
                    if (data.success == "1") {

                        var timestamp = data.timestamp;
                        var noncestr = data.noncestr;
                        var signature = data.signature;
                        //通过config接口注入权限验证配置
                        wx.config({
                            debug: false,
                            appId: data.appId,
                            timestamp: timestamp.toString(),
                            nonceStr: noncestr,   //生成签名的随机串
                            signature: signature,  //签名
                            jsApiList: ['chooseImage', 'uploadImage', 'downloadImage']
                        });

                    } else {
                        alert(data.error);
                    }
                }
            });
验证通过后,可以调用手机选择图片接口

 //拍照或从手机相册中选图接口
        function wxChooseImage() {
            wx.chooseImage({
                count: 1,
                needResult: 1,
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                success: function (data) {
                    localIds = data.localIds[0].toString(); // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                    if (rh.tostr(localIds)) {
                        wxuploadImage(localIds);
                    }
                },
                fail: function (res) {
                    alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", "");
                }

            });
        }
  选择图片成功后,同时调用上传图片接口,加载图片,主要要保存下 mediaId字段

   备注:上传图片有效期3天,可用微信多媒体接口下载图片到自己的服务器!

//上传图片接口
        function wxuploadImage(e) {
           
            wx.uploadImage({
                localId: e, // 需要上传的图片的本地ID,由chooseImage接口获得
                isShowProgressTips: 1, // 默认为1,显示进度提示
                success: function (res) {
                    mediaId = res.serverId; // 返回图片的服务器端ID
                    if (rh.tostr(mediaId)) {
                        $(".myimg").attr("src", localIds);
                    }

                },
                fail: function (error) {
                    picPath = '';
                    localIds = '';
                    alert(Json.stringify(error));

                }

            });
        }
 最后正式入库的时候,要通过mediaId从腾讯服务器中,下载到本地服务器:

$.ajax({
                        url: "test.ashx",
                        data: {
                            name: "getPicInfo",
                            media: $.trim(mediaId)
                        },
                        type: "Get",
                        dataType: "text",
                        success: function (data) {
                            picPath = data; //picPath gets the path of the picture
                          
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert("Submission failed" + textStatus);
                        }

                    });
By accessing the background interface, and also through the WeChat interface

var url = string.Format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", token, media);
var PicPath = Common.GetWxPic(url, "").ToString();
<pre name="code" class="csharp"> public static string GetWxPic(string url,string data)
        {
            string path = "";
            try
            {
                ServicePointManager.Expect100Continue = false;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (data == "" ? "" : "?" + data));
                request.Method = "GET";
                
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if(response.StatusCode  == HttpStatusCode.OK)
                    {
                        string fileName = Common.RightStr(response.Headers["Content-disposition"],"filename=",false).Replace("\"","");
                        path = "/uploadfile/" + fileName;
                        
                        Stream responseStream = response.GetResponseStream();
                        BinaryReader br = new BinaryReader(responseStream);
                        
                        FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Create, FileAccess.Write);

                        const int buffsize = 1024;
                        byte[] bytes = new byte[buffsize];
                        int totalread = 0;

                        int numread = buffsize;
                        while (numread != 0)
                        {
                            // read from source
                            numread = br.Read(bytes, 0, buffsize);
                            totalread += numread;

                            // write to disk
                            fs.Write(bytes, 0, numread);
                        }

                        br.Close();
                        fs.Close();

                        response.Close();

                    }
                    else
                    {
                        response.Close();
                        path = "";
                    }
                    
                }
            }
            catch (Exception)
            {
                path = "";
            }
            return path;
        }


 
 

保存图片到本地服务器上,即可:



完整代码下载






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325376413&siteId=291194637