參數(shù)
? |
描述 |
#appId |
公眾號碼的唯一標(biāo)識應(yīng)用id |
timestamp |
#產(chǎn)生簽章的時間戳記 |
nonceStr |
產(chǎn)生簽章的隨機串 |
signature |
簽名 |
#上述表格中的四個參數(shù)是初始化呼叫微信jsapi的憑證,咱們在前幾節(jié)已經(jīng)反覆說明如何使用了,在這裡就不在貼出如何產(chǎn)生上述四個參數(shù)了
完整的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>基礎(chǔ)接口之判斷當(dāng)前客戶端是否支持指定的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">預(yù)覽圖片接口</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>
顯示圖片<img src="/static/imghw/default1.png" data-src=""id=" class="lazy" alt=""id="faceImg"data-bd-imgshare-binded="1">
<br>
<script type="text/javascript">
wx.config({
debug: true, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。
appId: '${appId}', // 必填,公眾號的唯一標(biāo)識
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 圖片預(yù)覽
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接口 狀態(tài)
wx.error(function (res) {
alert("調(diào)用微信jsapi返回的狀態(tài):"+res.errMsg);
});
</script>
</body>
</html>
|
#1,上述程式碼html按鈕程式碼功能已經(jīng)描述的很清楚了,每點擊一個按鈕觸發(fā)一個js功能函數(shù)。
2、點擊上傳圖片按鈕之前首先要點擊選擇圖片按鈕功能,上傳圖片成功後會返回serverid,所以本人認為這裡非常梗,調(diào)用微信jsapi上傳接口,我的圖片到底上傳到哪裡去了呢?其實我們把圖片上傳到微信伺服器上了也就是臨時素材裡面去了,可登陸微信官方管理平臺查看,你也可以呼叫微信臨時素材介面取得圖片。
3、透過以上程式碼,我們就已經(jīng)把圖片上傳到微信伺服器了,但是我們上傳到微信伺服器的圖片只能保存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 {
/**
* 根據(jù)內(nèi)容類型判斷文件擴展名
*
* @param contentType 內(nèi)容類型
* @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 文件在本地服務(wù)器上的存儲路徑
* */
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 += "/";
}
// 根據(jù)內(nèi)容類型獲取擴展名
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="你公眾號基本設(shè)置里的應(yīng)用id";//應(yīng)用ID
String appSecret="你公眾號基本設(shè)置里的應(yīng)用密鑰";//(應(yīng)用密鑰)
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

以上是微信開發(fā)之微信jsapi選擇圖片,上傳圖片,預(yù)覽與下載圖片方法的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!