Micro-letter Jssdk upload pictures _javascript tips

Source: Internet
Author: User
Tags documentation ticket

Shortly before, the micro-letter disclosed some interfaces, including a uploadimage interface for uploading images, and generally used with chooseimage interfaces. First call the Chooseimage interface lets the user select one or more pictures, the user selects after the micro-letter will return the selected picture's ID, then the picture ID passes to the Uploadimage interface to upload the picture.

A recent project, just used to JSSDK, the use of things sorted out.

Link to the micro-trust developer Documentation: micro-trust Developer documentation

The main use of:

Introduction of JS File

In the need to call the JS interface page to introduce the following JS file, (support HTTPS): Http://res.wx.qq.com/open/js/jweixin-1.0.0.js

We need to get the micro-js-sdk parameters

/** * Obtain Access_token * * @param appid * Certificate * @param appsecret * key * @return/public static 
  Wxaccesstoken Getaccesstoken () {Wxaccesstoken accesstoken = null; String Requesturl = Access_token_url.replace ("APPID", Setting.getsetting ("wx_pl_app_id")). Replace ("Appsecret", Set 
  Ting.getsetting ("App_secret")); 
  Jsonobject jsonobject = HttpRequest (Requesturl, "get", null); 
      If the request succeeds if (null!= jsonobject) {try {Accesstoken = new Wxaccesstoken (); 
      Accesstoken.settoken (jsonobject.getstring ("Access_token")); 
    Accesstoken.setexpiresin (Jsonobject.getint ("expires_in")); 
      catch (Jsonexception e) {accesstoken = null; Get token failed log.error ("Get token failed errcode:{} errmsg:{}", Jsonobject.getint ("Errcode"), Jsonob 
    Ject.getstring ("ErrMsg")); 
} return Accesstoken; public static String Jsapiticket = "Https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCess_token&type=jsapi "; /** * Get jsticket * * @param accesstoken * Accesstoken * @return/public static Wxjsticket Getjsticket (String Accesstoken) 
  {Wxjsticket jsticket = null; 
  String url = jsapiticket.replaceall ("Access_token", Accesstoken); 
  Jsonobject jsonobject = HttpRequest (URL, "get", null); 
      If the request succeeds if (null!= jsonobject) {try {jsticket = new wxjsticket (); 
      Jsticket.setticket (jsonobject.getstring ("Ticket")); 
    Jsticket.setexpiresin (Jsonobject.getint ("expires_in")); 
      catch (Jsonexception e) {jsticket = null; 
          Get token failed Log.error ("Get Jsapiticket failed errcode:{} errmsg:{}", Jsonobject.getint ("Errcode"), 
    Jsonobject.getstring ("ErrMsg")); 
} return jsticket;  }

Note that the number of calls to the interface is limited and needs to be controlled well.

The configuration of the page

Wx.config ({ 
   debug:false,//Open debug mode, the return value of all invoked APIs will be on the client alert, to view incoming parameters, can be opened on the PC side, the parameter information will be typed through the log, only on the PC side will print.) 
   appId: "$! {wxsign.get (' appId ')} ",//required, unique identification of public number 
   timestamp:" $!{ Wxsign.get (' TimeStamp ')} ",//required, generate signature timestamp 
   noncestr:" $!{ Wxsign.get (' Noncestr ')} ",//required to generate a random string of signatures 
   signature:" $!{ Wxsign.get (' signature ')} ",/must be filled, signed, see Appendix 1 
   jsapilist: [' Checkjsapi ', 
         ' chooseimage ', ' 
         previewimage ', 
         ' uploadimage ']//must be filled in, need to use the JS interface list, all JS interface list see Appendix 2 
 }); 
 
 var images = { 
  localid: [], 
  serverid: [] 
 

Take a picture or select an interface from a mobile album

Wx.chooseimage ({
  count:1,//Default 9
  sizetype: [' original ', ' compressed '],//can specify whether it is an original or a compressed image, the default is both
  sourcetype : [' album ', ' Camera '],//You can specify whether the source is an album or a camera, both of which have
  success:function (res) {
    var localids = res.localids;//Return the selected photo's local ID list, localid can be used as the SRC attribute of the IMG tag to display the picture
  }
});

Upload Image interface

Wx.uploadimage ({
  localid: "///////
  /////////////////////////////) Success:function (res) {
    var serverid = Res.serverid;//Return the server-side ID of the picture}
});

Micro-letter return ServerID We need to get real image binary data through the micro-trust API.

/** * Get Media file * * @param accesstoken * Interface Access voucher * @param media_id * media file ID * */public static Stri Ng Downloadmedia (string mediaid,httpservletrequest request) {string requesturl = ' Http://file.api.weixin.qq.com/cgi-b 
  IN/MEDIA/GET?ACCESS_TOKEN=ACCESS_TOKEN&MEDIA_ID=MEDIA_ID "; Requesturl = Requesturl.replace ("Access_token", WxTokenThread.accessToken.getToken ()). Replace ("media_id", MediaId) 
  ; 
  HttpURLConnection conn = null; 
    try {URL url = new URL (requesturl); 
    conn = (httpurlconnection) url.openconnection (); 
    Conn.setdoinput (TRUE); 
    Conn.setrequestmethod ("get"); 
    Conn.setconnecttimeout (30000); 
    Conn.setreadtimeout (30000); 
    Bufferedinputstream bis = new Bufferedinputstream (Conn.getinputstream ());  
    Bytearrayoutputstream Swapstream = new Bytearrayoutputstream ();  
    byte[] buff = new byte[100];  
    int rc = 0; while (rc = bis.read (buff, 0)) > 0) {swapstream.write (buff, 0, RC);  
    } byte[] Filebyte = Swapstream.tobytearray (); 
  Return Picturestore.getinstance (). Getimageserverurl () + picturestore.getinstance (). Store (Filebyte); 
  catch (Exception e) {e.printstacktrace (); 
    finally {if (conn!= null) {conn.disconnect (); 
} return "";  }

The overall function is relatively simple, but has not previously been exposed to the micro-trust API.

Micro-letter Jssdk upload more than one picture

The code is as follows:

Jssdk

$ (' #filePicker '). On (' click ', Function () {
 wx.chooseimage ({
  success:function (res) {
   var localids = Res.localids;
   Syncupload (localids)
;}}); var syncupload = function (localids) {
 var localid = Localids.pop ();
 Wx.uploadimage ({
  localid:localid,
  isshowprogresstips:1,
  success:function (res) {
   var serverid = Res.serverid; Returns the server-side ID of the picture
   //other code that handles the ServerID
   if (localids.length > 0) {
    syncupload (localids);
   }}
 ) ;
};

This article to share the micro-letter Jssdk upload pictures of the method, I hope that the future work of everyone to learn help, of course, more than one of the methods, there are many, welcome to share their experience.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.