呼叫微信上傳圖片介面和下載圖片介面
阿新 • • 發佈:2019-02-15
目的:呼叫微信上傳圖片介面上傳圖片,並呼叫下載圖片介面下載到本地
1、繫結域名
登入微信公眾平臺後,進入 公眾號設定--》公眾號設定頁面如圖(1),點選設定如圖(2),輸入域名後,點選儲存。
注意:一定要MP_verify_3mOny5Qgj4Owoq0K.txt檔案上傳到域名所指的伺服器中,如果是tomcat的話,就放在tomcat的webapp目錄下即可。
圖(1)
圖(2)
3、通過config介面注入許可權驗證配置
wx.config({
debug: true, // 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。
appId: '${appId }', // 必填,公眾號的唯一標識
timestamp: '${timestamp}', // 必填,生成簽名的時間戳
nonceStr: '${nonceStr}', // 必填,生成簽名的隨機串
signature: '${signature}',// 必填,簽名
jsApiList: ['chooseImage','uploadImage'] // 必填,需要使用的JS介面列表
});
上面具體獲取引數的方法見:
https://blog.csdn.net/qq_33157666/article/details/80158519
4、通過ready介面處理成功驗證
上傳一張圖片:
html:
js:<div class="weui_cell"> <div class="weui_cell_hd"><label class="weui_label text_size">頭像</label></div> <div class="weui_cell_bd weui_cell_primary"> <img id="headPicture" src="" class="weui-avatar" onerror="fdp.defaultImage('${ctxfs}/shop_init/user_face_01.png');"/> </div> <div class="weui_cell_ft"> <i class="weui_icon_warn"></i> </div> </div>
wx.ready(function(){ //點選上傳圖片按鈕 $("body").delegate("#headPicture",'click',function(e){ var images = {localId:[],serverId:[]}; //最多可上傳圖片圖片數 var count=1; //呼叫 拍照或從手機相簿中選圖介面 24 wx.chooseImage({ count: count,//最多可上傳5張 success: function(res) { var imgUrl=res.localIds[0]; $("#headPicture").attr("src",imgUrl); //呼叫上傳圖片介面 images.localIds= res.localIds; var upload = function() { wx.uploadImage({ localId:images.localIds[0], success: function(res) { $(".serverIds").val(res.serverId); } }); }; upload(); } }); }); });
上傳多張圖:
html:
<div class="weui_cell weui_cell_img">
<div class="weui_uploader">
<div class="weui_uploader_bd">
<ul class="weui_uploader_files comment_imgs" id='img2'>
<div class="addCommentImg">
<span class="icon icon-xiangji1"></span>
<span class="commentImgcount">新增圖片</span>
</div>
</ul>
</div>
</div>
</div>
js:wx.ready(function(){
//點選上傳圖片按鈕
$("body").delegate(".addCommentImg",'click',function(e){
var images = {localId:[],serverId:[]};
//最多可上傳圖片圖片數
var count=5-$(this).siblings(".comment_img").length;
//存放圖片id的input
var $serverIds_input=$(this).parents(".weui_panel").find("input.serverIds");
var $comment_imgs=$(this);
//顯示已上傳圖片個數的span
var $commentImgcount=$(this).find("span.commentImgcount");
//獲取圖片id
var serverIds=$serverIds_input.val();
//呼叫 拍照或從手機相簿中選圖介面
wx.chooseImage({
count: count,//最多可上傳5張
success: function(res) {
var comment_img_Tpl=$("#comment_img_Tpl").html();
var commentImgHtml="";
//用js模板拼接圖片到頁面中
for(var i=0;i<res.localIds.length;i++){
var commentImgData={"imgUrl":res.localIds[i]};//模板的資料
commentImgHtml+=wx_common.render(comment_img_Tpl,commentImgData);//渲染模板
}
$comment_imgs.before(commentImgHtml);
//已上傳圖片的數量
var validCount=$comment_imgs.siblings(".comment_img").length;
$commentImgcount.text(validCount+" / "+5);
//超過5張隱藏上傳按鈕
if(validCount==5){
$commentImgcount.parent().addClass("hide");
}
//呼叫上傳圖片介面
images.localIds= res.localIds;
var i = 0; var length = images.localIds.length;//迴圈上傳多個圖片
var upload = function() {
wx.uploadImage({
localId:images.localIds[i],
success: function(res) {
serverIds+=res.serverId+",";
images.serverId.push(res.serverId);
$serverIds_input.val(serverIds);
//如果還有照片,繼續上傳
i++;
if (i < length) {
upload();
}
}
});
};
upload();
}
});
});
});
至此,上傳已經完成,但是這是將圖片上傳到了微信伺服器,我們需要將存到我們自己的伺服器中,所以需要經圖片下載到我們的伺服器中。
5、下載圖片
/**
* 下載圖片
* @param mediaIds 圖片在微信伺服器上對應的id
* @param $imgPath_input 存圖片地址的input
* */
function downloadImg (mediaIds,$imgPath_input){
var flag=false;
if(typeof(mediaIds)=="undefined" || mediaIds==""){
layer.closeAll();
layer.open({content: 'mediaIds不能為空',skin: 'msg',time: 2});
return flag;
}
var token=weixin.getToken();
if(token=="" || token==null){
layer.closeAll();
layer.open({content: 'token不能為空',skin: 'msg',time: 2});
return flag;
}
$.ajax({
url:"xxxxxxxxxxxxxxx",
type:'POST',
data:{"accessToken":"xxxx","mediaIds":mediaIds,},
dataType:'json',
async: false,
success:function(data){
if(data==null || !data.status || data.path==""){
return;
}
//下載成功後,將返回的圖片地址存到頁面的隱藏域中
var paths=$imgPath_input.val();
$imgPath_input.val(paths+data.path);
flag=true;
}
});
return flag;
}
java程式碼:
public Map<String,Object> downloadImage(String accessToken,String mediaIds) {
Map<String,Object> map=new HashMap<>();
if(StringUtils.isBlank(accessToken)){
map.put("status",false);
map.put("message","檔案下載失敗,accessToken不能為空");
return map;
}
if(StringUtils.isBlank(mediaIds)){
map.put("status",false);
map.put("message","imgId不能為空");
return map;
}
if(",".equals(mediaIds.substring(0,1))){
mediaIds=mediaIds.substring(1,mediaIds.length());
}
String localFilePath="";
logger.info("mediaIds:"+mediaIds);
String[] media=mediaIds.split(",");
logger.info("media:"+media);
if(media.length>0){
for(int i=0;i<media.length;i++){
// 拼接請求地址
String requestUrl =
"http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+accessToken+"&media_id="+media[i];
URL url;
BufferedInputStream bis=null;
HttpURLConnection conn=null;
try{
url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
// 根據內容型別獲取副檔名
String fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
FileStorage lf=FileStorageFcatory.get();
// 將mediaId作為檔名
bis = new BufferedInputStream(conn.getInputStream());
}
String fileName="xxxxxxx";//圖片儲存路徑
File file=new File( fileName+fileExt);
localFilePath+=FileUtils.copyInputStreamToFile(bis,file)+",";
}catch (Exception e){
logger.error("下載圖片失敗", e);
map.put("status",false);
map.put("message","下載圖片出現錯誤");
return map;
}finally{
try{
bis.close();
conn.disconnect();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
if(StringUtils.isNotBlank(localFilePath)){
if(",".equals(localFilePath.substring(localFilePath.length()-1,localFilePath.length()))){
localFilePath=localFilePath.substring(0,localFilePath.length()-1);
}
}
map.put("status", true);
map.put("message","下載成功");
map.put("path", localFilePath);
return map;
}