最近有需求做到公眾號開發,有一個上傳圖片的功能,查看了微信公眾號的開發文檔,故做如下記錄。
公眾號中上傳圖片的大概流程是:
1、調用config接口注入權限(接口標識具體參考微信公眾平台的附錄,我這邊需要注入chooseImage、uploadImage)
wx.config({ // debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 appId: appId, // 必填,公眾號的唯一標識 timestamp: timestamp, // 必填,生成簽名的時間戳 nonceStr: nonceStr, // 必填,生成簽名的隨機串 signature: signature,// 必填,簽名,見附錄1 jsApiList: ['chooseImage','uploadImage'] // 必填,需要使用的JS接口列表,所有JS接口列表見微信公眾平台附錄 });
2、調用選擇圖片(chooseImage)的接口啟用選擇手機圖片的功能,選擇完圖片后調用上傳接口(uploadImage)上傳圖片到微信的服務器,返回serverId
var that = this,imageLength=9;
var image={localIds:[],serverId:[]}; //接收微信接口返回的參數
var imageUrlList=[] //用戶綁定頁面上顯示圖片的變量
var mediaIds=[] //接收上傳圖片返回的serverId(該字段就是調用獲取臨時素材接口的媒體ID)
//1.選擇圖片
wx.chooseImage({
count: imageLength, //上傳圖片的張數,最多上傳9張
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
success: function(res) {
that.images.localIds = res.localIds;
//展示圖片
for (var i=0;i<res.localIds.length;i++) {
that.imageUrlList.push(res.localIds[i]);
}
var uploadCount = 0;
var localIdLength = that.images.localIds.length;
var upload = function() {
// 2.上傳圖片
wx.uploadImage({
localId:that.images.localIds[uploadCount], //選擇的圖片標識
success: function(res) {
that.images.serverId.push(res.serverId); //微信返回的該圖片的服務ID,可調用獲取素材的接口下載到自己項目的應用服務器
var mediaIdsLength = that.mediaIds.length;
var flag = false;
if (mediaIdsLength>0) {
for (var i=0;i<mediaIdsLength;i++) {
if (that.mediaIds[i].id == value.id) {
that.mediaIds[i].mediaId.push(res.serverId);
}
flag = true;
}
}
if (!flag) {
var item = {id:'',mediaId:[]};
item.id = value.id;item.mediaId.push(res.serverId);
that.mediaIds.push(item);
}
//如果還有照片,繼續上傳
uploadCount++;
if (uploadCount < localIdLength) {
upload();
}
},
fail: function(res) {
alert(JSON.stringify(res));
}
});
};
//循環上傳
upload();
},
fail: function(res) {
alert(JSON.stringify(res));
}
});
3、最后調用獲取臨時素材的接口,
http請求方式: GET,https調用
https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
請求示例(示例為通過curl命令獲取多媒體文件)
curl -I -G "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"
access_token:接口調用憑證
media_id:媒體ID,(上傳圖片返回的serverId)
接口返回:
{
"video_url":DOWN_URL
}
