微信 java 实现js-sdk 图片上传下载完整流程
最近做的一个项目刚好用到微信js-sdk的图片上传接口,在这里做一下总结。
在这里能知道使用jsapi的基本配置
https://mp.weixin.qq.com/wiki
t=resource/res_main&id=mp1421141115&token=&lang=zh_CN
我这里没有用checkJsApi去判断当前客户端版本是否支持指定JS接口,好。通过看开发文档,我们知道调用js接口直接都要通过config接口注入权限验证配置
<codeclass="hljscs">wx.config({ debug:true,//开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId:'',//必填,公众号的唯一标识 timestamp:,//必填,生成签名的时间戳 nonceStr:'',//必填,生成签名的随机串 signature:'',//必填,签名,见附录1 jsApiList:[]//必填,需要使用的JS接口列表,所有JS接口列表见附录2 });</code>
获取config里面参数的代码如下,我这里只用到chooseImage和uploadImage接口,chooseImage接口是拍照或从手机相册中选图接口,uploadImage接口是用来上传图片,所以jsApiList里面只写这两个就可以了
<codeclass="hljsavrasm">importjava.util.UUID; importjava.util.Map; importjava.util.HashMap; importjava.util.Formatter; importjava.security.MessageDigest; importjava.security.NoSuchAlgorithmException; importjava.io.UnsupportedEncodingException; publicclassWxConfig{ publicstaticvoidmain(String[]args){ Stringjsapi_ticket="jsapi_ticket"; //注意URL一定要动态获取,不能hardcode Stringurl="http://example.com"; Map<string,string="">ret=sign(jsapi_ticket,url); for(Map.Entryentry:ret.entrySet()){ System.out.println(entry.getKey()+","+entry.getValue()); } }; publicstaticMap<string,string="">sign(Stringjsapi_ticket,Stringurl){ Map<string,string="">ret=newHashMap<string,string="">(); Stringnonce_str=create_nonce_str(); Stringtimestamp=create_timestamp(); Stringstring1; Stringsignature=""; //注意这里参数名必须全部小写,且必须有序 string1="jsapi_ticket="+jsapi_ticket+ "&noncestr="+nonce_str+ "×tamp="+timestamp+ "&url="+url; System.out.println(string1); try { MessageDigestcrypt=MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature=byteToHex(crypt.digest()); } catch(NoSuchAlgorithmExceptione) { e.printStackTrace(); } catch(UnsupportedEncodingExceptione) { 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); returnret; } privatestaticStringbyteToHex(finalbyte[]hash){ Formatterformatter=newFormatter(); for(byteb:hash) { formatter.format("%02x",b); } Stringresult=formatter.toString(); formatter.close(); returnresult; } privatestaticStringcreate_nonce_str(){ returnUUID.randomUUID().toString(); } privatestaticStringcreate_timestamp(){ returnLong.toString(System.currentTimeMillis()/1000); } } </string,></string,></string,></string,></code>
ticket可以通过accessToken获取,代码如下
<codeclass="hljscs">publicstaticStringgetTicket(StringaccessToken)throwsParseException,IOException{ publicfinalstaticStringsign_ticket_create_url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; JSONObjectjsonObject=newJSONObject(); JSONObjectpostjson=newJSONObject(); Stringticket=null; Stringurl=sign_ticket_create_url.replace("ACCESS_TOKEN",accessToken); System.out.print("url="+url); Stringticketurl=""; try{ jsonObject=WeixinUtil.httpsRequest(url,"POST",postjson.toString()); ticket=jsonObject.getString("ticket"); System.out.println("ticket:"+ticket); }catch(Exceptione){ e.printStackTrace(); } returnticket; };</code>
当注入权限验证成功的时候会进入ready接口,那么我们就在ready接口里面继续我们需要的操作
<codeclass="hljsjavascript">wx.ready(function(){ //拍照或从手机相册中选图接口 wx.chooseImage({ count:1,//最多能选择多少张图片,默认9 sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认二者都有 sourceType:['album','camera'],//可以指定来源是相册还是相机,默认二者都有 success:function(res){ varlocalIds=res.localIds;//返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 //上传图片接口 wx.uploadImage({ localId:localIds.toString(),//需要上传的图片的本地ID,由chooseImage接口获得 isShowProgressTips:1,//默认为1,显示进度提示 success:function(res){ varserverId=res.serverId;//返回图片的服务器端ID } }); } }); });</code>
通过以上代码,我们就已经把图片上传到微信服务器了,但是我们上传到微信服务器的图片只能保存3天,所以上传完之后我们要把图片下载到我们的本地服务器,这里用到微信下载多媒体接口
http://file.api.weixin.qq.com/cgi-bin/media/get?
access_token=ACCESS_TOKEN&media_id=MEDIA_ID
其中media_id就是我们上面的serverId,所以我们就可以把图片下载到本地了,代码如下
<codeclass="hljsjava">importorg.apache.log4j.Level; importorg.apache.log4j.LogManager; importorg.apache.log4j.Logger; importorg.apache.log4j.Priority; importorg.springframework.util.StringUtils; importjava.io.*; importjava.net.HttpURLConnection; importjava.net.URL; importjava.net.URLConnection; publicclassDloadImgUtil{ /** *根据内容类型判断文件扩展名 * *@paramcontentType内容类型 *@return */ publicstaticStringgetFileexpandedName(StringcontentType){ StringfileEndWitsh=""; if("image/jpeg".equals(contentType)) fileEndWitsh=".jpg"; elseif("audio/mpeg".equals(contentType)) fileEndWitsh=".mp3"; elseif("audio/amr".equals(contentType)) fileEndWitsh=".amr"; elseif("video/mp4".equals(contentType)) fileEndWitsh=".mp4"; elseif("video/mpeg4".equals(contentType)) fileEndWitsh=".mp4"; returnfileEndWitsh; } /** *获取媒体文件 *@paramaccessToken接口访问凭证 *@parammediaId媒体文件id *@paramsavePath文件在本地服务器上的存储路径 **/ publicstaticStringdownloadMedia(StringaccessToken,StringmediaId,StringsavePath){ try{ accessToken=WeixinUtil.getAccessToken1().getToken(); }catch(IOExceptione){ e.printStackTrace(); } StringfilePath=null; //拼接请求地址 StringrequestUrl="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{ URLurl=newURL(requestUrl); HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.setRequestMethod("GET"); if(!savePath.endsWith("/")){ savePath+="/"; } //根据内容类型获取扩展名 StringfileExt=DloadImgUtil.getFileexpandedName(conn.getHeaderField("Content-Type")); //将mediaId作为文件名 filePath=savePath+mediaId+fileExt; BufferedInputStreambis=newBufferedInputStream(conn.getInputStream()); FileOutputStreamfos=newFileOutputStream(newFile(filePath)); byte[]buf=newbyte[8096]; intsize=0; while((size=bis.read(buf))!=-1) fos.write(buf,0,size); fos.close(); bis.close(); conn.disconnect(); Stringinfo=String.format("下载媒体文件成功,filePath="+filePath); System.out.println(info); }catch(Exceptione){ filePath=null; Stringerror=String.format("下载媒体文件失败:%s",e); System.out.println(error); } returnfilePath; } } </code>
这样就完成了js-sdk图片上传下载了。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!