微信開發(fā)之調(diào)起攝像頭、本地展示圖片、上傳下載圖片實(shí)例
之前那篇微信JS-SDK授權(quán)的文章實(shí)現(xiàn)了分享接口,那么這里總結(jié)一下如何在微信里面通過(guò)js調(diào)起原生攝像頭,以及上傳下載圖片。
1.配置
頁(yè)面引入通過(guò)jssdk授權(quán)后,傳入wx對(duì)象,首先配置需要的接口
wx.config({
/* debug: true, */
appId: appid,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: [
'chooseImage',//拍照或從手機(jī)相冊(cè)中選圖接口
'previewImage',//預(yù)覽圖片接口
'uploadImage',//上傳圖片接口
'downloadImage'//下載圖片接口
]
});
2.調(diào)起拍照/相冊(cè)
將下面的方法放在需要點(diǎn)擊事件的回調(diào)函數(shù)里面
wx.chooseImage({
count: 1, //張數(shù), 默認(rèn)9
sizeType: ['compressed'], //建議壓縮圖
sourceType: ['album', 'camera'], // 來(lái)源是相冊(cè)、相機(jī)
success: function (res) {
//var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作為img標(biāo)簽的src屬性顯示圖片
$('.driver-card img').prop('src',res.localIds[0]);
uploadPhoto.uploadToWeixinServer(res.localIds[0],'car')
}
});
這時(shí)我們可以看到這樣的效果,代表調(diào)起成功了!chooseImage方法的成功回調(diào)里,我將選中的照片賦值給需要顯示的img的src(因?yàn)槲疫@里只有一張照片,如果有多張用循環(huán)賦值即可),這樣一來(lái),就可以直接顯示剛剛拍照/相冊(cè)里選中的照片了
3.上傳照片
在上面chooseImage的success回調(diào)里面,可以看到我調(diào)用了uploadToWeixinServer方法,參數(shù)為本地照片的Id
uploadToWeixinServer: function(localId,type){
wx.uploadImage({
localId: localId,
isShowProgressTips: 1, // 默認(rèn)為1,顯示進(jìn)度提示
success: function (res) {
//res.serverId 返回圖片的微信服務(wù)器端ID
uploadPhoto.uploadToOwnerServer(res.serverId,type);//異步上傳到我們自己的服務(wù)器
}
});
},
調(diào)用uploadImage接口后,將圖片上傳到了微信服務(wù)器,返回圖片的ID,這個(gè)時(shí)候需要用ajax異步上傳到自己的服務(wù)器里,調(diào)用微信提供的“獲取臨時(shí)素材”接口。當(dāng)然也不一定是選擇完照片就立即上傳,還得根據(jù)實(shí)際業(yè)務(wù)需求出發(fā),也有是靜默上傳(沒(méi)有進(jìn)度提示),也有是在最終提交表單時(shí)一起上傳
js:
uploadToOwnerServer: function(serverId,type){
$.ajax({
data: {serverId:serverId,type:type},
type : "POST",
url : WX_ROOT + "wechat/uploadPhoto",
success : function(json) {
if (json) {
var data = JSON.parse(json.data);
if ('car' == type)
uploadPhoto.options.carImage = data.path + data.name
else
uploadPhoto.options.idCardImage = data.path + data.name
}
}
});
},
Controller
@RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
public @ResponseBody HttpResult uploadPhoto(@RequestParam String serverId,@RequestParam String type) throws Exception{
LOGGER.info("RestFul of uploadPhoto parameters serverId:{},type:{}",serverId,type);
try {
/** 將圖片保存到本地服務(wù)器 **/
String photoName = type + new Date().getTime() + UUID.randomUUID().toString();
//文件路徑不存在則創(chuàng)建
File saveFile = new File(PIC_PATH + type);
if (!saveFile.mkdir()) saveFile.mkdir();
wechatService.saveImageToDisk(serverId, photoName, PIC_PATH + type + "/");
LOGGER.info("Download the picture from weixin server pathL:{}",PIC_PATH + type + "/");
JSONObject data = new JSONObject();
data.put("name", type + "/" + photoName+".jpg");
data.put("path", PIC_SERVER + "/");
HttpResult rs = new HttpResult();
rs.setCode(200);
rs.setData(data.toJSONString());
LOGGER.info("Download the picture from weixin server is successful!serverId:{},photoName:{}",serverId,photoName);
LOGGER.info("HttpResult data:{}",rs.getData());
return rs;
} catch (Exception e) {
LOGGER.error("Download the picture from weixin server is error",serverId);
return null;
}
這里我使用了一個(gè)UUID生成主鍵規(guī)則,通過(guò)類型+時(shí)間戳+唯一字符串定義圖片名稱。如果上傳成功,同時(shí)又將自己服務(wù)器的圖片地址返回給前端。
getInputStream
調(diào)用微信提供的獲取臨時(shí)素材接口下載還在微信服務(wù)器上的圖片,參數(shù)為前端提交上來(lái)的媒體文件ID,最終將文件轉(zhuǎn)化為輸入流對(duì)象
/**
* 根據(jù)文件id下載文件
* @param accessToken
* @param mediaId
* @return 文件流對(duì)象
*/
public InputStream getInputStream(String accessToken, String mediaId) {
InputStream is = null;
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+ accessToken + "&media_id=" + mediaId;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請(qǐng)求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接超時(shí)30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取超時(shí)30秒
http.connect();
// 獲取文件轉(zhuǎn)化為byte流
is = http.getInputStream();
} catch (Exception e) {
LOGGER.error("Failed to convert inputStream from weixin server,accessToken:{},mediaId:{}",accessToken,mediaId);
}
return is;
}
service
通過(guò)循環(huán)解析流對(duì)象,將文件寫入自己的服務(wù)器
public void saveImageToDisk(String mediaId, String picName, String picPath) throws Exception {
String accessToken = getBaseAccessToken();
InputStream inputStream = getInputStream(accessToken, mediaId);
// 循環(huán)取出流中的數(shù)據(jù)
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(picPath+picName+".jpg");
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
LOGGER.info("Write the fileInputStream is successful");
} catch (IOException e) {
LOGGER.error("Write the fileInputStream is error");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error("Close the fileInputStream is error");
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
LOGGER.error("Close the fileOutputStream is error");
}
}
}
}
4.總結(jié)
那么到這里,簡(jiǎn)單的拍照,展示圖片,上傳下載的功能都已經(jīng)完成,其實(shí)代碼就是最好的注釋!微信開放的jssdk提供了很多友好而有趣的功能,接下來(lái)還需要繼續(xù)實(shí)踐研究....
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript作用域深度剖析之動(dòng)態(tài)作用域
這篇文章主要為大家介紹了?JavaScript作用域?qū)W習(xí)之動(dòng)態(tài)作用域深度剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
使用bootstrap實(shí)現(xiàn)下拉框搜索功能的實(shí)例講解
今天小編就為大家分享一篇使用bootstrap實(shí)現(xiàn)下拉框搜索功能的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
移動(dòng)Web中圖片自適應(yīng)的兩種JavaScript解決方法
這篇文章主要介紹了移動(dòng)Web中圖片自適應(yīng)的兩種JavaScript解決方法,本文針對(duì)手機(jī)站點(diǎn)中的圖片自適應(yīng)問(wèn)題,給出了圖集解決方法和單篇文章的解決方法,需要的朋友可以參考下2015-06-06
Bootstrap3 Grid system原理及應(yīng)用詳解
這篇文章主要為大家詳細(xì)介紹了Bootstrap3 Grid system原理及應(yīng)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
提高團(tuán)隊(duì)代碼質(zhì)量利器ESLint及Prettier詳解
這篇文章主要為大家介紹了提高團(tuán)隊(duì)代碼質(zhì)量利器ESLint及Prettier使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
用xhtml+css寫的相冊(cè)自適應(yīng) - 類似九宮格[兼容 ff ie6 ie7 opear ]
用xhtml+css寫的相冊(cè)自適應(yīng) - 類似九宮格[兼容 ff ie6 ie7 opear ]...2007-05-05
深入學(xué)習(xí)js函數(shù)的隱式參數(shù) arguments 和 this
這篇文章主要介紹了 深入學(xué)習(xí)js函數(shù)的隱式參數(shù) arguments 和 this,arguments是一個(gè)類數(shù)組結(jié)構(gòu),它保存了調(diào)用時(shí)傳遞給函數(shù)的所有實(shí)參;this是函數(shù)執(zhí)行時(shí)的上下文對(duì)象, 這個(gè)對(duì)象有些讓人感到困惑的行為。 下面分別對(duì)他們進(jìn)行討論。,需要的朋友可以參考下2019-06-06

