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

微信开发之微信jsapi选择图片,上传图片,预览和下载图片方法

参数
  描述
appid 公众号的唯一标识  应用id
timestamp 生成签名的时间戳
noncestr 生成签名的随机串
signature 签名
上述表格中的四个参数是初始化调用微信jsapi的凭证,咱们在前几节已经反复说明如何使用了,在这里就不在贴出如何生成上述四个参数了
完整的jsp代码如下:
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> <% string path = request.getcontextpath(); string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <base href="<%=basepath%>"> <title>微信jsapi测试-v型知识库</title> <meta name="viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"> </script> <scriptsrc="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> </head> <body> <center><h3>欢迎来到微信jsapi测试界面-v型知识库</h3></center> <p>基础接口之判断当前客户端是否支持指定的js接口</p> <input type="button" value="checkjsapi" id="checkjsapi"><br> <h3 id="menu-image">图像接口</h3> <span class="desc">拍照或从手机相册中选图接口</span><br> <button class="btn btn_primary" id="chooseimage">chooseimage</button><br> <span class="desc">预览图片接口</span><br> <button class="btn btn_primary" id="previewimage">previewimage</button><br> <span class="desc">上传图片接口</span><br> <button class="btn btn_primary" id="uploadimage">uploadimage</button><br> <span class="desc">下载图片接口</span><br> <button class="btn btn_primary" id="downloadimage">downloadimage</button><br> 显示图片<imgalt=""src=""id="faceimg"data-bd-imgshare-binded="1"> <br> <script type="text/javascript"> wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appid: '${appid}', // 必填,公众号的唯一标识 timestamp: '${ timestamp}' , // 必填,生成签名的时间戳 noncestr: '${ noncestr}', // 必填,生成签名的随机串 signature: '${ signature}',// 必填,签名,见附录1 jsapilist: ['checkjsapi', 'chooseimage', 'previewimage', 'uploadimage', 'downloadimage' ] // 必填,需要使用的js接口列表,所有js接口列表见附录2 }); wx.ready(function(){ // 5 图片接口 // 5.1 拍照、本地选图 var images = { localid: [], serverid: [] }; document.queryselector('#chooseimage').onclick = function () { wx.chooseimage({ success: function (res) { images.localid = res.localids; alert('已选择 ' + res.localids.length + ' 张图片'); $("#faceimg").attr("src", res.localids[0]);//显示图片到页面上 } }); }; // 5.2 图片预览 document.queryselector('#previewimage').onclick = function () { wx.previewimage({ current: 'http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg', urls: [ 'http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg', 'http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg', 'http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg' ] }); }; // 5.3 上传图片 document.queryselector('#uploadimage').onclick = function () { if (images.localid.length == 0) { alert('请先使用 chooseimage 接口选择图片'); return; } var i = 0, length = images.localid.length; images.serverid = []; function upload() { wx.uploadimage({ localid: images.localid[i], success: function (res) { i++; //alert('已上传:' + i + '/' + length); images.serverid.push(res.serverid); if (i < length) { upload(); } }, fail: function (res) { alert(json.stringify(res)); } }); } upload(); }; // 5.4 下载图片 document.queryselector('#downloadimage').onclick = function () { if (images.serverid.length === 0) { alert('请先使用 uploadimage 上传图片'); return; } var i = 0, length = images.serverid.length; images.localid = []; function download() { wx.downloadimage({ serverid: images.serverid[i], success: function (res) { i++; alert('已下载:' + i + '/' + length); images.localid.push(res.localid); if (i < length) { download(); } } }); } download(); }; }); //初始化jsapi接口 状态 wx.error(function (res) { alert("调用微信jsapi返回的状态:"+res.errmsg); }); </script> </body> </html>
1,上述代码html按钮代码功能已经描述的很清楚了,每点击一个按钮触发一个js功能函数。
2、点击上传图片按钮之前首先要点击选择图片按钮功能,上传图片成功后会返回serverid,所以本人认为这里非常梗,调用微信jsapi上传接口,我的图片到底上传到哪里去了呢?实际上我们把图片上传到微信服务器上了也就是临时素材里面去了,可登陆微信官方管理平台查看,你也可以调用微信临时素材接口获取图片。
3、通过以上代码,我们就已经把图片上传到微信服务器了,但是我们上传到微信服务器的图片只能保存3天,所以上传完之后我们要把图片下载到我们的本地服务器,这里用到微信下载多媒体接口http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=access_token&media_id=media_id 其中media_id就是我们上面的serverid ,所以我们就可以把图片下载到本地了,代码如下
package com.test.weixin; import net.sf.json.jsonobject; 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.malformedurlexception; import java.net.url; import java.net.urlconnection; /**** * * @author v型知识库 www.vxzsk.com * */ 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 = dloadimgutil.getaccesstoken(); } 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; } /*** * 获取acess_token * 来源www.vxzsk.com * @return */ public static string getaccesstoken(){ string appid="你公众号基本设置里的应用id";//应用id string appsecret="你公众号基本设置里的应用密钥";//(应用密钥) string url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret+""; string backdata=dloadimgutil.sendget(url, "utf-8", 10000); string accesstoken = (string) jsonobject.fromobject(backdata).get("access_token"); return accesstoken; } /*** * 模拟get请求 * @param url * @param charset * @param timeout * @return */ public static string sendget(string url, string charset, int timeout) { string result = ""; try { url u = new url(url); try { urlconnection conn = u.openconnection(); conn.connect(); conn.setconnecttimeout(timeout); bufferedreader in = new bufferedreader(new inputstreamreader(conn.getinputstream(), charset)); string line=""; while ((line = in.readline()) != null) { result = result + line; } in.close(); } catch (ioexception e) { return result; } } catch (malformedurlexception e) { return result; } return result; } }
效果图如下:
选择图片弹出的图片详情
上传成功后返回的serverid
以上就是微信开发之微信jsapi选择图片,上传图片,预览和下载图片方法的详细内容。
其它类似信息

推荐信息