您好,欢迎访问一九零五行业门户网

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

最近做的一个项目刚好用到微信js-sdk的图片上传接口,在这里做一下总结。
在这里能知道使用js api的基本配置
https://mp.weixin.qq.com/wiki
t=resource/res_main&id=mp1421141115&token=&lang=zh_cn
我这里没有用checkjsapi去判断当前客户端版本是否支持指定js接口,好。通过看开发文档,我们知道调用js接口直接都要通过config接口注入权限验证配置
<code class="hljs cs">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里面只写这两个就可以了
<code class="hljs avrasm">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 + "×tamp=" + 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); } } </string,></string,></string,></string,></code>
ticket可以通过accesstoken获取,代码如下
<code class="hljs cs">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; };</code>
当注入权限验证成功的时候会进入ready接口,那么我们就在ready接口里面继续我们需要的操作
<code class="hljs javascript">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 } }); } }); });</code>
通过以上代码,我们就已经把图片上传到微信服务器了,但是我们上传到微信服务器的图片只能保存3天,所以上传完之后我们要把图片下载到我们的本地服务器,这里用到微信下载多媒体接口
http://file.api.weixin.qq.com/cgi-bin/media/get?
access_token=access_token&media_id=media_id
其中media_id就是我们上面的serverid ,所以我们就可以把图片下载到本地了,代码如下
<code class="hljs java">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; } } </code>
这样就完成了js-sdk图片上传下载了。
其它类似信息

推荐信息