微信公众号上传图片

微信公众号上传图片

调用图像接口的js详情请见微信接口文档:
http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html

多媒体文件下载:
http://mp.weixin.qq.com/wiki/12/58bfcfabbd501c7cd77c19bd9cfa8354.html

此处记录微信公众号内上传图片以及用多媒体接口从微信服务器下载图片的过程。
调用图像接口的js代码:

调用微信接口需要获取签名,具体操作,详见:
http://blog.csdn.net/u013121551/article/details/62426106

jsp简略代码如下:

<!-- 预览 -->
<img class="" id="previewImage" src="" alt=""/>
<!-- 上传 -->
 <div class="" id="chooseImage">
     <div class="">
         <!-- 显示加号的样式,可根据自己页面需求定义 -->
         <i class="icon icon-plus"></i>
     </div>
     <p class="tc textCard">上传图片</p>
 </div>
wx.config({
     debug: false,
     appId: '<%=RequestParam.APP_ID%>',
     timestamp: '<%=params.get("time") %>', //生成签名的时间戳
     nonceStr: '<%=params.get("randomStr") %>', //生成签名的随机串
     signature: '<%=params.get("signature") %>', //签名
     jsApiList: [
       'chooseImage',
       'previewImage',
       'uploadImage',
       'downloadImage'
     ]
 });
wx.ready(function() {
 // 5 图片接口
    // 5.1 拍照、本地选图
    var images = {
      localId: [],
      serverId: []
    };
    document.querySelector('#chooseImage').onclick = function () {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
        success: function (res) {
          images.localId = res.localIds;
          alert(res.localIds);
          alert('已选择 ' + res.localIds.length + ' 张图片');
          /*for(){

          }*/
          //上传成功后,图片的id会被存储在res中返回,可以进行预览
          $("#previewImage").attr("src",res.localIds);
        }
      });
    };

    // 5.2 图片预览
    document.querySelector('#previewImage').onclick = function () {
        var url = basePath + "/" + $("#previewImage").attr("src");
//      alert(url);
        wx.previewImage({
            current: url,
            urls: [
               url
               ]
        });
    };

    // 5.3 上传图片
    document.querySelector('#uploadImage').onclick = function () {
      if (images.localId.length == 0) {
        alert('请先选择图片');
        return;
      }
      var i = 0, length = images.localId.length;
      images.serverId = [];
      function upload() {
        wx.uploadImage({
          localId: images.localId[i],
          success: function (res) {
            alert(res.serverId);
            i++;
            alert('已上传:' + i + '/' + length);
            images.serverId.push(res.serverId);
            //多媒体接口下载到本地服务器
            $.ajax({
                    url : '',  //进行多媒体下载的url
                    type : 'post',       //请求方式post
                    dataType : 'text',   //返回的数据类型 
                    data : {mediaId:res.serverId},           //请求时的参数
                    error : function () {//请求失败后的回调
//                    alert("why");
                      location.reload();
                    },
                    success : function (data) {  //请求成功后的操作

                    }
                })
            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();
    };
});

图片上传步骤基本上是js完成,图片上传后是上传到微信服务器,所以要在上传成功后,将图片从微信服务器中下载下来。

public String downLoad(@Param("mediaId") String mediaId){
    try{
        //2、下载微信服务器上的名片信息,存入数据库
        Map<String,Object> map = WXAPIUtils.getMedia(mediaId);
        if(map != null){
        //为了获取文件名和类型
            contentDisposition = map.get("Content-disposition")+"";
            byte[] content=null;
            if(map.get("content") instanceof byte[]){
                 content = (byte[]) map.get("content") ;
            }
            filenameAndType = contentDisposition.substring(contentDisposition.indexOf("=")+2,contentDisposition.length()-1).split("\\.");
        //存入数据库

        }catch(Exception e){
            e.printStackTrace();
        }
    }

多媒体下载

/**
 * 多媒体接口下载文件
 * @param mediaId
 * @return
 */
public static Map<String,Object> getMedia(String mediaId){

    String mediaUrl = WX_MEDIA+"?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
    String requestUrl = mediaUrl.replace("ACCESS_TOKEN", access_token)
    .replace("MEDIA_ID", mediaId);

    System.out.println(requestUrl);
    //发送get请求
    try{
        Map<String,Object> resp = HttpRequestUtils.getHttp(requestUrl, "UTF-8", "UTF-8");
        return resp;

    }catch(Exception e){
        e.printStackTrace();
        return null;
    }

}

多媒体文件下载接口,需要通过http的get请求请求url:
http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
参数:access_token:调用接口凭证。获取签名时已经获取,需缓存下来。
media_id:媒体文件。需要下载的没提文件。

接口请求正常后,返回http头包括下列内容:
HTTP/1.1 200 OK
Connection: close
Content-Type: image/jpeg
Content-disposition: attachment; filename=”MEDIA_ID.jpg”
Date: Sun, 06 Jan 2013 10:20:18 GMT
Cache-Control: no-cache, must-revalidate
Content-Length: 339721
curl -G “http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID

错误时返回:
{“errcode”:40007,”errmsg”:”invalid media_id”}

http请求的代码如下:

/**
         * get方式
         * 
         * @param url
         *            请求地址
         * @param requestEncoding
         *            请求发送编码
         * @param responseEncoding
         *            接受结果编码
         * @return
         * @throws ParseException
         * @throws IOException
         */
    public static Map<String,Object> getHttp(String url, String requestEncoding, String responseEncoding) throws ParseException, IOException {
        Map<String,Object> map = new HashMap<String,Object>();
        HttpClient http = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse resp = http.execute(get);
            //获取HTTP头信息
            Header[] headers = resp.getAllHeaders();
            for(int i = 0;i<headers.length;i++){
                if(headers[i].getName() != null){
                    map.put(headers[i].getName(), headers[i].getValue());
                }
            }
            HttpEntity entity = resp.getEntity();
            byte[] test=EntityUtils.toByteArray(entity);
            map.put("content", test);
            // 该处 encoding 为返回结果编码
//          return EntityUtils.toString(entity, responseEncoding);
            return map;
        } finally {
            // 关闭连接,释放资源
            http.getConnectionManager().shutdown();
        }

    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值