java微信开发之--更换背景图片

本文介绍如何使用Java进行微信开发,专注于更换背景图片的功能。在资源稀缺的情况下,作者分享了微博上的经验和博客内容,强调了微信API文档的重要性。文章包括页面代码和后台代码的实现细节,旨在帮助开发者理解和实现类似功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 在刚开始写关于微信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]来生成目录:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值