WeChat js-sdk image upload and download - java complete process

A recent project just used the image upload interface of WeChat js-sdk, so I will make a summary here.
Here you can know the basic configuration of using js api https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN
I did not use checkJsApi here to judge whether the current client version supports the specified JS interface, ok. By looking at the development documentation, we know that calling the js interface directly requires injecting the permission verification configuration through the config interface

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

The code to obtain the parameters in the config is as follows. I only use the chooseImage and uploadImage interfaces here. The chooseImage interface is used to take pictures or select pictures from the mobile phone album, and the uploadImage interface is used to upload pictures, so just write these two in jsApiList.

import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

public class WxConfig {
    public static void main(String[] args) {
        String jsapi_ticket = "jsapi_ticket";

        // 注意 URL 一定要动态获取,不能 hardcode
        String url = "http://example.com";
        Map<String, String> ret = sign(jsapi_ticket, url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
    };

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}

Ticket can be obtained through accessToken, the code is as follows

public static String getTicket(String accessToken) throws ParseException, IOException {
        public final static String sign_ticket_create_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        JSONObject jsonObject = new JSONObject();
        JSONObject postjson=new JSONObject();
        String ticket =null;
        String url = sign_ticket_create_url.replace("ACCESS_TOKEN",accessToken);
        System.out.print("url="+url);
        String ticketurl ="";
        try {
            jsonObject = WeixinUtil.httpsRequest(url, "POST",postjson.toString());
            ticket= jsonObject.getString("ticket");
            System.out.println("ticket:"+ticket);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    };

When the injection permission verification is successful, the ready interface will be entered, then we will continue the operations we need in the ready interface.

wx.ready(function(){
        //拍照或从手机相册中选图接口
        wx.chooseImage({
            count: 1, // 最多能选择多少张图片,默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function (res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                //上传图片接口
                wx.uploadImage({
                    localId: localIds.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
                    isShowProgressTips: 1, // 默认为1,显示进度提示
                    success: function (res) {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                    }
                });
            }
        });
    });

Through the above code, we have already uploaded the picture to the WeChat server, but the pictures we uploaded to the WeChat server can only be saved for 3 days, so after uploading, we need to download the pictures to our local server, here we use WeChat to download multimedia Interface http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
where media_id is our serverId above, so we can download the picture to the local, the code is as follows

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class DloadImgUtil {
  /**
   * 根据内容类型判断文件扩展名
   *
   * @param contentType 内容类型
   * @return
   */
  public static String getFileexpandedName(String contentType) {
    String fileEndWitsh = "";
    if ("image/jpeg".equals(contentType))
      fileEndWitsh = ".jpg";
    else if ("audio/mpeg".equals(contentType))
      fileEndWitsh = ".mp3";
    else if ("audio/amr".equals(contentType))
      fileEndWitsh = ".amr";
    else if ("video/mp4".equals(contentType))
      fileEndWitsh = ".mp4";
    else if ("video/mpeg4".equals(contentType))
      fileEndWitsh = ".mp4";
    return fileEndWitsh;
  }
  /**
   * 获取媒体文件
   * @param accessToken 接口访问凭证
   * @param mediaId 媒体文件id
   * @param savePath 文件在本地服务器上的存储路径
   * */
  public static String downloadMedia(String accessToken, String mediaId, String savePath) {
    try {
      accessToken = WeixinUtil.getAccessToken1().getToken();
    } catch (IOException e) {
      e.printStackTrace();
    }
    String filePath = null;
    // 拼接请求地址
    String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
    requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoInput(true);
      conn.setRequestMethod("GET");

      if (!savePath.endsWith("/")) {
        savePath += "/";
      }
      // 根据内容类型获取扩展名
      String fileExt = DloadImgUtil .getFileexpandedName(conn.getHeaderField("Content-Type"));
      // 将mediaId作为文件名
      filePath = savePath + mediaId + fileExt;
      BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
      FileOutputStream fos = new FileOutputStream(new File(filePath));
      byte[] buf = new byte[8096];
      int size = 0;
      while ((size = bis.read(buf)) != -1)
        fos.write(buf, 0, size);
      fos.close();
      bis.close();

      conn.disconnect();
      String info = String.format("下载媒体文件成功,filePath=" + filePath);
      System.out.println(info);
    } catch (Exception e) {
      filePath = null;
      String error = String.format("下载媒体文件失败:%s", e);
      System.out.println(error);
    }
    return filePath;
  }
}

This completes the upload and download of js-sdk images.

Guess you like

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