java微信開發之--更換背景圖片

  • 在剛開始寫關於微信jsapi的時候可以說是一竅不通
  • 資源又少於是我果斷上傳微博希望對大家開發微信有幫助
  • 同時也把東西寫到博客裏沒事就多看看也好

微信開發API文檔是必看的

在api文檔裏面我們可以看到很多內容,然後需要我們去理解點擊進微信硬件平臺api[http://iot.weixin.qq.com/wiki/new/index.html?page=4-7.

頁面代碼塊

代碼塊語法遵循標準markdown代碼:

<html>
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/jquery-1.2.6.pack.js">
</script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js">
</script>

<div id="uploadImage">
    <img  id="zhuye" src="PersonImg/${personImg}"/>
    <div><font>點擊更換主頁</font></div>
</div>


<script type="text/javascript">
//config接口權限配置 這裏在文檔是有清晰的解不知道的可以看我的第一篇博客

wx.config( {
//都是從後臺傳過來的值
beta : true, // 開啓內測接口調用,注入wx.invoke方法必填
debug : true, // 開啓調試模式 必填
appId : '${config.appId}', // 第三方app唯一標識必填
timestamp : '${config.timestamp}', // 簽名的時間戳必填
nonceStr : '${config.nonce}', // 生成簽名的隨機串必填
signature : '${config.signature}',//簽名 必填
jsApiList : [
    //添加使用的函數
'chooseImage', 'uploadImage', 'downloadImage' ]
})//ready權限驗證
wx.ready(function () {
  // 5 圖片接口
  // 5.1 拍照、本地選圖
  var images = {
    localId: [],
    serverId: []
  };


  // 5.3 上傳圖片
  document.querySelector('#uploadImage').onclick = function () {
      //選擇圖片
         wx.chooseImage({success: function (res) {
             images.localId = res.localIds;

             if (res.localIds.length != 1) {
                         alert('只能上傳一張圖片');
                         return;
                    }
             else{
                    upload();   
             }

         }
         });
    }

      function upload() {
        //上傳圖片到自己服務器
        wx.uploadImage({
        localId: images.localId[0],
        success: function (res) {
             wxImgCallback(res.serverId);
        },
        fail: function (res) {
          alert('上傳失敗');
        }
      });
    }

function wxImgCallback(serverId) {
     //將serverId傳給wx_upload.php的upload方法
     var url = '${pageContext.request.contextPath}/bbs.do?method=uploadHeadImg';
     $.post(url,{serverIds : serverId}, function(data){
            if(data=="true"){
    document.getElementById("zhuye").src=images.localId[0];
            }
    });
}
});

</script>
</html>

//修改數據庫的個人主頁背景名稱
String imgNickname=path.substring(path.indexOf(“/”)+1,path.length());
usersService.updateUpersonImg(imgNickname,userId);
這裏如果沒有到數據庫可以不寫,隱藏即可

後臺代碼塊

代碼塊語法遵循標準markdown代碼:

    /**
     * 
     * 個人主頁更換
     * @return
     */
    @RequestMapping(params="method=uploadHeadImg")
    public String uploadHeadImg(HttpServletResponse response){
        //得到用戶名
        String userId=(String) request.getSession().getAttribute("userId");
        //得到頁面傳來的serverIds
        String serverId=request.getParameter("serverIds");
        // 要存在你服務器哪個位置?
        String Imgpath= request.getSession().getServletContext().getRealPath("PersonImg");
        //上傳的圖片以id命名
       String path=comradeService.downloadMedia(serverId, Imgpath,userId);

       //修改數據庫的個人主頁背景名稱
       String imgNickname=path.substring(path.indexOf("/")+1,path.length());
       usersService.updateUpersonImg(imgNickname,userId);

       response.setContentType("text/html;charset=utf-8");
       try {
        if(path!=null && path!=""){
                response.getWriter().print("true");
           }
           else {
               response.getWriter().print("false");
           }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      return null;
}       

/** 
     * 獲取媒體文件 
     * @param accessToken 接口訪問憑證 
     * @param media_id 媒體文件id 
     * @param savePath 文件在服務器上的存儲路徑 
     * */  
    public static String downloadMedia(String mediaId, String savePath,String userId) {  
        String struts=HttpUtil.getImgPathStuts(mediaId,savePath,userId);
        return struts;
    }  


/**
     * 
     * @param mediaId 多媒體在微信服務器的地址
     * @param savePath  保存的地址
     * @param userId    用戶關注公衆號唯一ID
     * @return
     */
    public static String getImgPathStuts(String mediaId, String savePath,String userId) {
        //下載圖片保存到哪裏,圖片名字什麼
        String imgPath = null;  
         // 拼接請求地址  
        String requestUrl = MpApi.UploadMediaUrl;  
        //得到ACCESS_TOKEN 這裏根據你怎麼自己項目的ACCESS_TOKEN 就行了
        requestUrl = requestUrl.replace("ACCESS_TOKEN", AccessTokenUtil.getTokenStr()).replace("MEDIA_ID", mediaId);  

        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            conn.setDoInput(true);  
            conn.setRequestMethod("GET");  
            if (!savePath.endsWith("/")) {  
                savePath += "/";  
            }  
            // 將用戶關注者id作爲文件名  
            imgPath = savePath +userId+".png";  
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
            FileOutputStream fos = new FileOutputStream(new File(imgPath));  
            byte[] buf = new byte[8096];  
            int size = 0;  
            while ((size = bis.read(buf)) != -1)  
                fos.write(buf, 0, size);  
            fos.close();  
            bis.close();  
            conn.disconnect();  
            String info = String.format("下載媒體文件成功,filePath=" + imgPath);    
        } catch (Exception e) {  
            imgPath = null;  
            String error = String.format("下載媒體文件失敗:%s", e);  
        }  
        return imgPath;
    }

    //多媒體下載接口
    public final static String UploadMediaUrl="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";

不懂可以去看文檔或者找其他資料,歡迎入羣(93472007)

目錄

[TOC]來生成目錄:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章