调用微信Js-SDK图片

1.Js代码:

$(document).ready(function(){
   var url = location.href.split('#')[0];
   var imgSrc = ""; $.get(rootPath
+ "/wechat/getWechatConfig?url=" + url,"",function(data){ wx.config({ debug: false, appId: data.appId, nonceStr: data.nonceStr, signature: data.signature, timestamp: parseInt(data.timestamp), jsApiList: [ 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard' ] }); }); wx.ready(function () { /** * 选择图片 */ document.querySelector('#id').onclick = function () { wx.chooseImage({ count: 1, // 可选择图片张数 success: function (res) { //alert("选择成功:" + res.localIds); setTimeout(function(){ wx.uploadImage({ localId: res.localIds.toString(), isShowProgressTips:1, success : function(res){ //alert("上传成功" + res.serverId); //上传成功后,图片在微信服务器保存7天,接下来将图片下载到自己服务器返回地址,格式如http://app.baidu.com/map/images/tiananmen.jpg,供图片预览
                $.get("/wechat/saveImg?mediaId=" + res.serverId.toString(),"",function(result){ if(result == ""){ alert("下载失败"); }else{ imgSrc = result; } }); }, fail: function(res){ alert("上传失败" + res.errMsg); } }); },100); } }); } /** * 预览图片 */ document.querySelector('#id').onclick = function () { wx.previewImage({ current: imgSrc, urls: [imgSrc] }); } //微信地图 document.querySelector('#mapBtn').onclick = function () { wx.getLocation({ success: function (res) { var longitude = res.longitude; // 纬度,浮点数,范围为90 ~ -90 var latitude = res.latitude; // 经度,浮点数,范围为180 ~ -180。 var speed = res.speed; // 速度,以米/每秒计 var accuracy = res.accuracy; // 位置精度 //alert("纬度:" + longitude +"---"+ "经度:" + latitude +"---"+ "速度:" + speed +"---"+ "位置:" + accuracy); wx.openLocation({ latitude: latitude, longitude: longitude, name: '我的位置', address: accuracy, scale: speed, infoUrl: 'http://weixin.qq.com' }); }, cancel: function (res) { alert('取消获取地理位置'); } }); }; }); wx.error(function (res) { alert(res.errMsg); }); });
//获取微信配置wx.config使用
public
static WechatConfig getWechatConfig(String url) throws Exception { System.out.println(UPLOAD_IMAGE_PATH); WechatConfig config = new WechatConfig(); config.setAppId(APPID); String nonceStr = UUID.randomUUID().toString().replaceAll("-", ""); config.setNonceStr(nonceStr); String timestamp = Long.toString(System.currentTimeMillis() / 1000); config.setTimestamp(timestamp); String str = "jsapi_ticket=" + getJsapiTicket().getTicket() + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url; MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(str.getBytes("UTF-8")); String signature = byteToHex(crypt.digest()); config.setSignature(signature); logger.info("wechatConfig:" + JsonMapper.toJsonString(config)); return config; } public static JsapiTicket getJsapiTicket() throws Exception { JsapiTicket jsapiTicket = new JsapiTicket(); String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; logger.info("获取JsapiTicket开始:"); JSONObject jsonObject = doGetStr(url); if (jsonObject != null) { jsapiTicket.setErrcode(jsonObject.getString("errcode")); jsapiTicket.setErrmsg(jsonObject.getString("errmsg")); jsapiTicket.setExpiresIn(jsonObject.getString("expires_in")); jsapiTicket.setTicket(jsonObject.getString("ticket")); } logger.info(JsonMapper.toJsonString(jsapiTicket)); return jsapiTicket; } 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; } public static JSONObject doGetStr(String url) throws ParseException, IOException { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); JSONObject jsonObject = null; HttpResponse httpResponse = client.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); jsonObject = JSONObject.parseObject(result); } return jsonObject; }
    /**
     * 从微信服务器下载,再上传到图片服务器
     * 
     * @return
     * @throws Exception
     */
    public static String saveImg(String mediaId) throws Exception {
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        logger.info("从微信服务器下载开始……");
        logger.info(url);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        HttpResponse httpResponse = client.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            logger.info("从微信服务器下载失败:"
                    + httpResponse.getStatusLine().getStatusCode());
            return "";
        }

        String fileName = "";
        String str = httpResponse.getFirstHeader("Content-disposition")
                .getValue();
        if (StringUtils.isNotEmpty(str) && str.indexOf(""") != -1) {
            fileName = str.substring(str.indexOf(""") + 1,
                    str.lastIndexOf("""));
            logger.info("从微信服务器下载成功:" + fileName);
        }
        String dateStr = "/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date());
        String path = "/usr/local/tomcat7/webapps" + dateStr;
        
        File file = new File(path);
        if(!file.exists())
            file.mkdirs();
        logger.info("保存的图片路径:" + path);
        
        HttpEntity entity = httpResponse.getEntity();
        InputStream is = null;
        FileOutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            is = entity.getContent();
            bos = new ByteArrayOutputStream(); 
            byte[] buffer = new byte[1024];
            int len = 0;  
            while( (len=is.read(buffer)) != -1 ){  
                bos.write(buffer, 0, len);  
            }
            fos = new FileOutputStream(path + "/" + fileName);
            fos.write(bos.toByteArray());
        } catch (Exception e) {
            logger.info("保存到图片服务器失败:" + e.fillInStackTrace());
            e.printStackTrace();
            return "";
        }finally{  
            is.close();  
            fos.close();  
        } 
        return PREVIEW_IMAGE_URL + dateStr + "/" + fileName;
    }

 

原文地址:https://www.cnblogs.com/linying/p/4974439.html