调用微信上传图片接口和下载图片接口

目的:调用微信上传图片接口上传图片,并调用下载图片接口下载到本地

1、绑定域名

登录微信公众平台后,进入 公众号设置--》公众号设置页面如图(1),点击设置如图(2),输入域名后,点击保存。

注意:一定要MP_verify_3mOny5Qgj4Owoq0K.txt文件上传到域名所指的服务器中,如果是tomcat的话,就放在tomcat的webapp目录下即可。


图(1)


图(2)

2、在需要调用接口的页面引入js: http://res.wx.qq.com/open/js/jweixin-1.2.0.js

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:

<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>
js:
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;
}

猜你喜欢

转载自blog.csdn.net/qq_33157666/article/details/79944812
今日推荐