当前位置: 首页 > 工具软件 > 晒图 > 使用案例 >

公众号评论晒图上传图片

陆仲渊
2023-12-01

一、首先获取调取微信js的签名

    1.通过ajax获取跳去微信签名所需要的签名(appid,timestamp,nonceStr,signature)   

  @ResponseBody
    @RequestMapping("qrCodeData")
    private static Object qrCodeData(HttpServletRequest req){
        SortedMap<String, String> params = new TreeMap<String, String>();
        params.put("timestamp", Sha1Util.getTimeStamp());//时间戳
        params.put("noncestr", UUIDS.genReqIDtoLowCase());//随机字符串
        params.put("url",req.getParameter("url"));//调取js的页面路径
        try {
        	String jsapi_ticket=RedisUtils.get("ticket");
        	if(StringUtils.isBlank(jsapi_ticket)){
        		 logger.error("**********jsapi_ticket为空**************");
        		jsapi_ticket=WechatAccessToken.GetTicket(RedisUtils.get("token"));
        	}
           params.put("jsapi_ticket", jsapi_ticket);//调取js的ticket
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error(e.toString());
        }
        RequestHandler rHandler = new RequestHandler();
        params.put("signature", rHandler.createSign(params, "SHA-1"));
        params.put("appid", WechatGlobalConfig.APP_ID);
        logger.info(params);
        return params;
    }

/**
 *SH1签名
 */
	public String createSign(SortedMap<String, String> packageParams,String encName) {		
		String[] paramArr = new String[] { "jsapi_ticket=" + 
        packageParams.get("jsapi_ticket"),"timestamp=" +  packageParams.get("timestamp"), 
        "noncestr=" + packageParams.get("noncestr"), "url=" + packageParams.get("url") };
		Arrays.sort(paramArr);
		// 将排序后的结果拼接成一个字符串
		String content =    
   paramArr[0].concat("&"+paramArr[1]).concat("&"+paramArr[2]).concat("&"+paramArr[3]);
		String sign = WXMD5.MD5Encode(content, encName);	
		return sign;

	}

    /**
     * MD5编码
     * @param origin 原始字符串
     * @return 经过MD5加密之后的结果
     */
    public static String MD5Encode(String origin, String encName) {
        String resultString = null;
        try {
            resultString = origin;
            if(encName == null || "".equals(encName)){
            	encName = "MD5";
            }
            MessageDigest md = MessageDigest.getInstance(encName);
            resultString = byteArrayToHexString(md.digest(resultString.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

二、评论页面引入微信js(http://res.wx.qq.com/open/js/jweixin-1.0.0.js; )

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
   function camera(){//点击晒图事件
	   if(!iscomment){ //是否已评论
		   var count=6-list.length;//可选照片6张减去已选的
		   $.ajax({
	           type : "POST",
	           data:{url:url},
	           url : "<%=basePath%>qrCode/qrCodeData",
	           dataType : "json",
	           success : function (data) {    
	              var appId = data.appid;
	              var timestamp = data.timestamp;
	              var nonceStr = data.noncestr;
	              var signature = data.signature; 
	              wx.config({
	                  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
	                  appId: appId, // 必填,公众号的唯一标识
	                  timestamp: timestamp, // 必填,生成签名的时间戳
	                  nonceStr: nonceStr, // 必填,生成签名的随机串
	                  signature:signature,// 必填,签名,见附录1
	                  jsApiList: ['chooseImage', 'uploadImage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
	              });
	               var images = {localIds:[],serverId:[]};
	                  wx.chooseImage({
	                      count: count,
	                      sizeType: ['original', 'compressed'],
	                      sourceType: ['album'],
	                      success: function(res) {
	                          images.localIds = res.localIds;
	                          var uploadCount = 0;
	                          var localIdLength = images.localIds.length;
	                          var m = 0;
	                          var upload = function() {
	                              wx.uploadImage({
	                                  localId:images.localIds[uploadCount],
	                                  success: function(res) {
	                                      images.serverId.push(res.serverId);
	                                      //如果还有照片,继续上传
	                                      //将获取到的 mediaId 传入后台 方法savePicture            
						                  $.post("<%=basePath%>shopsupplier/updoad/img",{mediaId:res.serverId},function(res){
						                 	  if(res.code == '000000'){
						                     	  list.push(res.data.imgPath);
						                     	  imgcount.innerHTML +='<img style="width:100px ;height:100px;" src="'+res.data.img+'"/>';//将上传的图片展示到页面
								                  if((list.length)>5){
								            		  $("#addimg").css("display","none"); 
								            	  }
						                       }
						                   })
						                   //这个方法是你需要把所谓的媒体meidaid进行下载到本地的ajax处理如果你需要的话就写一个ajax方法
	                                      uploadCount++;
	                                      if (uploadCount < localIdLength) {
	                                          upload();
	                                      }
	                                  }
	                              });                    
	                          };
	                          upload();
	                      }
	                  }); 
	           }
		  });
	   }
   }

三、将微信返回的图片id传给后台,重新下载并上传到自己的服务器

		@ResponseBody
		@DataSourceAuth(validate=DatasourceConfig.dataSourceA)
		@RequestMapping(value="/updoad/img",method ={RequestMethod.POST},produces="application/json;charset=utf-8")
		public Map<String,Object> uploadImg(HttpServletRequest req){
			String mediaId=req.getParameter("mediaId");
			AccessToken AT=WechatAccessToken.getAccessToken(null, null);
			String access_token = AT.getToken();
		    String params = "access_token=" + access_token + "&media_id=" + mediaId;
		    String url = "https://api.weixin.qq.com/cgi-bin/media/get";
			InputStream is = null;
	       try {
	        String urlNameString = url + "?" + params;
	           URL urlGet = new URL(urlNameString);
	           HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
	           http.setRequestMethod("GET"); // 必须是get方式请求
	           http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	           http.setDoOutput(true);
	           http.setDoInput(true);
	           http.connect();
	           // 获取文件转化为byte流
	           is = http.getInputStream();
	       } catch (Exception e) {
	           e.printStackTrace();
	       }
          
			return ssService.uploadImg(is);
		}

service实现类:

	@Override
	public Map<String,Object> uploadImg(InputStream in) {
		try {
			if(in==null){
				return JsonUtil.errorJsonMessageMap(ErrorsCodeConfigure.ERROR_CODE, StringConfigure.UPLOAD_ERROR);
			}
			String imgPath=ImgPath.shopComment + "/";
			Date a=new Date();
			String picName = CodeUtil.createCharacter(7)+a.getTime()+".png";

			boolean pb = false;
			try {
				pb = SFTPUtil.upload(imgPath + SFTPUtil.getPathStr() , picName, in);//上传到ftp服务器
			} catch (SftpException e) {
				e.printStackTrace();
			}
			if (pb) {
				String img=FtpUtils.IMG_URL + ImgPath.shopComment + "/"+SFTPUtil.getPathStr()+ picName;
				Map<String,String> m=new HashMap<String,String>();
				m.put("img", img);
				m.put("imgPath",SFTPUtil.getPathStr()+ picName);
				return JsonUtil.successJsonMessageMap(SuccessCodeConfigure.SUCCESS_CODE,StringConfigure.SUCCESS_INFO,m);
			}
		} catch (Exception e) {
			return JsonUtil.errorJsonMessageMap(ErrorsCodeConfigure.ERROR_CODE, StringConfigure.UPLOAD_ERROR);
		}
		return JsonUtil.errorJsonMessageMap(ErrorsCodeConfigure.ERROR_CODE, StringConfigure.UPLOAD_ERROR);
		
	}

 

四、注意事项

     在上传多张图片时,ios只上传一张照片,我采用的是for循环会出现这种状况,在网上搜了下,具体是什么原因导致的还不清楚,只是采用递归的方法实现了需求,有知道的大神还请指教!谢谢

 类似资料: