SoFunction
Updated on 2025-02-28

Upload pictures on WeChat JSSDK

Not long ago, WeChat disclosed some interfaces, one of which is an uploadImage interface for uploading images, which is generally used in conjunction with the choiceImage interface. First call the choiceImage interface and let the user select one or more pictures. After the user selects, WeChat will return the id of the selected picture, and then pass the image id to the uploadImage interface to upload the picture.

A project I recently worked on happened to use JSSDK and sorted out the things I used.

First attach the link to the WeChat developer document:WeChat developer documentation

Mainly used:

Introduce JS files

Introduce the following JS file to the page that needs to call the JS interface (support https):/open/js/jweixin-1.0.

We need to get the WeChat js-sdk parameters

/**
  * Get access_token
  *
  * @param appid
  * Voucher
  * @param appsecret
  * Key
  * @return
  */ 
public static WxAccessToken getAccessToken() { 
  WxAccessToken accessToken = null; 
  String requestUrl = access_token_url.replace("APPID", ("WX_PL_APP_ID")).replace( 
      "APPSECRET", ("APP_SECRET")); 
  JSONObject jsonObject = httpRequest(requestUrl, "GET", null); 
  // If the request is successful  if (null != jsonObject) { 
    try { 
      accessToken = new WxAccessToken(); 
      (("access_token")); 
      (("expires_in")); 
    } catch (JSONException e) { 
      accessToken = null; 
      // Failed to get token      ("Gettokenfail errcode:{} errmsg:{}", 
          ("errcode"), 
          ("errmsg")); 
    } 
  } 
  return accessToken; 
} 
public static String jsapiTicket = "/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 = ("ACCESS_TOKEN", accessToken); 
  JSONObject jsonObject = httpRequest(url, "GET", null); 
  // If the request is successful  if (null != jsonObject) { 
    try { 
      jsTicket = new WxJsTicket(); 
      (("ticket")); 
      (("expires_in")); 
    } catch (JSONException e) { 
      jsTicket = null; 
      // Failed to get token      ("GetjsapiTicketfail errcode:{} errmsg:{}", 
          ("errcode"), 
          ("errmsg")); 
    } 
  } 
  return jsTicket; 
} 

It should be noted that the number of calls to the interface is limited and needs to be controlled well.

Page configuration

({ 
   debug: false, // Turn on debug mode, the return values ​​of all APIs called will be alerted on the client. To view the passed parameters, you can open them on the PC side. The parameter information will be printed through the log and will only be printed on the PC side.   appId: "$!{('appId')}", // Required, unique identification of the official account   timestamp: "$!{('timeStamp')}", // Required to generate a signature time stamp   nonceStr: "$!{('nonceStr')}", // Required to generate a random string of signatures   signature: "$!{('signature')}",// Required, signature, see Appendix 1   jsApiList: ['checkJsApi', 
         'chooseImage', 
         'previewImage', 
         'uploadImage'] // Required, a list of JS interfaces that need to be used, and the list of all JS interfaces is shown in Appendix 2 }); 
 
 var images = { 
  localId: [], 
  serverId: [] 
 }; 

Take a picture or select a picture from your mobile phone album

({
  count: 1, // Default 9  sizeType: ['original', 'compressed'], // You can specify whether it is an original or a compressed image, and both are default  sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera, and both are default  success: function (res) {
    var localIds = ; // Return the local ID list of the selected photo. LocalId can display the picture as the src attribute of the img tag.  }
});

Upload image interface

({
  localId: '', // The local ID of the image to be uploaded is obtained from the choiceImage interface  isShowProgressTips: 1, // Default is 1, display progress prompts  success: function (res) {
    var serverId = ; // Return the server ID of the picture  }
});

For the serverid returned by WeChat, we need to obtain the real image binary data through the WeChat API.

/**
  * Get media files
  *
  * @param accessToken
  * Interface access credentials
  * @param media_id
  * Media file id
  * */ 
public static String downloadMedia(String mediaId,HttpServletRequest request) { 
  String requestUrl = "/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; 
  requestUrl = ("ACCESS_TOKEN", ()).replace( 
      "MEDIA_ID", mediaId); 
  HttpURLConnection conn = null; 
  try { 
    URL url = new URL(requestUrl); 
    conn = (HttpURLConnection) (); 
    (true); 
    ("GET"); 
    (30000); 
    (30000); 
    BufferedInputStream bis = new BufferedInputStream( 
        ()); 
    ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
    byte[] buff = new byte[100];  
    int rc = 0;  
    while ((rc = (buff, 0, 100)) > 0) {  
      (buff, 0, rc);  
    }  
    byte[] filebyte = ();  
    return ().getImageServerUrl() + ().store(filebyte); 
  } catch (Exception e) { 
    (); 
  } finally { 
    if(conn != null){ 
      (); 
    } 
  } 
  return ""; 
} 

Overall, it is relatively simple to do this function, but I have never been exposed to the WeChat API before.

WeChat jssdk upload multiple pictures

The code is as follows:

jssdk

$('#filePicker').on('click', function () {
 ({
  success: function (res) {
   var localIds = ;
   syncUpload(localIds);
  }
 });
});
var syncUpload = function(localIds){
 var localId = ();
 ({
  localId: localId,
  isShowProgressTips: 1,
  success: function (res) {
   var serverId = ; // Return the server ID of the picture   //Other codes for processing serverId   if( > 0){
    syncUpload(localIds);
   }
  }
 });
};

This article shares with you the method of uploading pictures on WeChat JSSDK. I hope it will be helpful to your future work and study. Of course, there are more than one method, and there are many more. Everyone is welcome to share their experiences.