微信js-sdk图片上传下载——java完整流程

最近做的一个项目刚好用到微信js-sdk的图片上传接口,在这里做一下总结。
在这里能知道使用js api的基本配置https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN
我这里没有用checkJsApi去判断当前客户端版本是否支持指定JS接口,好。通过看开发文档,我们知道调用js接口直接都要通过config接口注入权限验证配置

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

获取config里面参数的代码如下,我这里只用到chooseImage和uploadImage接口,chooseImage接口是拍照或从手机相册中选图接口,uploadImage接口是用来上传图片,所以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可以通过accessToken获取,代码如下

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;
    };

当注入权限验证成功的时候会进入ready接口,那么我们就在ready接口里面继续我们需要的操作

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
                    }
                });
            }
        });
    });

通过以上代码,我们就已经把图片上传到微信服务器了,但是我们上传到微信服务器的图片只能保存3天,所以上传完之后我们要把图片下载到我们的本地服务器,这里用到微信下载多媒体接口http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
其中media_id就是我们上面的serverId ,所以我们就可以把图片下载到本地了,代码如下

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;
  }
}

这样就完成了js-sdk图片上传下载了。

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值