实现微信公众号微信头像上传

这次我们做的项目需要实现一个微信公众号头像上传并且剪裁的功能,实在没有头绪,之后通过网上搜索和自己的修改实现了一个适合我们这个框架的方法。

首先本次项目我们的页面用的事velocity框架,页面代码是:

	
  • js代码如下:
    
    var voice = {
            localId: '',
            serverId: ''
        };
        wx.config({
            debug: false,
            appId: '${weixin.appId}',
            timestamp: '${weixin.timestamp}',
            nonceStr: '${weixin.nonceStr}',
            signature: '${weixin.signature}',
            jsApiList: [
                'chooseImage', 'uploadImage','openLocation','getLocation','scanQRCode','startRecord',
                'stopRecord',
                'onVoiceRecordEnd',
                'playVoice',
                'onVoicePlayEnd',
                'pauseVoice',
                'stopVoice',
                'uploadVoice',
                'downloadVoice'
            ]
        });
    wx.ready(function () {
    // 5 图片接口
                // 5.1 拍照、本地选图
                var images = {
                    localId: [],
                    serverId: []
                };
                document.querySelector('#diyUploadimg').onclick = function () {
                    alert(1)
                    wx.chooseImage({
                        count: 1,
                        success: function (res) {
                            images.localId = res.localIds;
                            uploadImg();
                        }
                    });
                };
    
    
    
    
    
                // 5.3 上传图片
                function uploadImg() {
    
                    if (images.localId.length == 0) {
                        alert('请先使用 chooseImage 接口选择图片');
                        return;
                    }
                    var i = 0, length = images.localId.length;
                    images.serverId = [];
                    function upload() {
                        wx.uploadImage({
                            localId: images.localId[i],
                            success: function (res) {
                                i++;
                                //alert('已上传:' + i + '/' + length);
                                images.serverId.push(res.serverId);
                                if (i < length) {
                                    upload();
                                }else{
                                    wxImgCallback();
                                }
                            },
                            fail: function (res) {
                                alert(JSON.stringify(res));
                            }
                        });
                    }
                    upload();
                };
                var tag=0;
                function wxImgCallback() {
                    $.ajax({
                        type : "get",
                        async : false,//变异步为同步
                        url : "wx_uploadImg.html",
                        data : {
                            "imgServerId" : images.serverId[0]
                        },
                        success : function(data) {
                            window.location.href='/wx/headImg.html?imgurl='+data;
                            tag=1;
                        }
                    });
                }
            });
    以上就是此功能的上传头像页面的html与js代码,下面是上传头像的Java代码,
    		ApiConfig config = new ApiConfig(Constant.appId, Constant.appSecret);
    		// 微信照片上传功能
    		String ticket = config.getJsApiTicket();
    		String code = request.getParameter("code");
    		String url= baseurl+"/wx/teacherBaseInfo.html";//注意此处路径需要与本页面路径完全一致,如果需要变得		                                                  页面跳转到此页面参数也必须保持一致
    		Weixin w = WeixinUtil.sign(ticket, url);
    		modelMap.addAttribute("weixin", w);
    以上是微信端实现头像上传的所有代码可能少了一部分,今天时间有限后续补上。下面贴出头像剪裁代码

    首先是html代码:

    [Jcrop Example]
    下面是js代码:

    最后是Java部分头像剪裁代码:
    	@RequestMapping("/cutImage.json")
    	@ResponseBody//注意此处,我用的springboot框架,此方法一定要加上这个注释,我就是忽略了返回值不能是总是不对脑			 残了
    	public Map cutImage(ModelMap modelMap, HttpServletRequest request, String srcImg, String destImg, int x, int y, int width, int height){
    		Map result = new HashMap();
    		WxUser	tp = (WxUser) request.getSession().getAttribute("wxUser");//此处调通后开放
    		//图片的相对路径
    		String imagPath=request.getParameter("srcImg");
    		String fileRealPath = request.getSession().getServletContext().getRealPath("/") ;
            System.out.println("图片路径:"+fileRealPath);
    //        String fileRealPath="d://";
    		String newFileName= UUID.randomUUID()+".jpg";
    		//实际图片路径
    		String img = imagPath.replaceAll(baseurl,"");
    		String path1=fileRealPath+img;
    		//裁剪后存储到服务器的图片路径
    		String path2=fileRealPath+"upload/weixin/"+newFileName;
    		System.out.println("图片路径:"+path1);
    		System.out.println("输出路径:"+path2);
    		try{
    			CutImage(path1, path2, x, y, width, height);
    			if("0".equals(tp.getType())){
    				WxUser wxUser = wxUserService.findById(tp.getId().toString());
    				String url = "/upload/weixin"+path2.substring(path2.lastIndexOf("/"));
    				wxUser.setHeadImg(url);
    				wxUserService.update(wxUser);
    				result.put("type","0");
    			}else {
    				WxUserParent wxUserParent = wxUserParentService.findById(tp.getId().toString());
    				String url = "/upload/weixin"+path2.substring(path2.lastIndexOf("/"));
    				wxUserParent.setHeadImg(url);
    				wxUserParentService.update(wxUserParent);
    				result.put("type","1");
    			}
    			result.put("code",0);
    			result.put("msg","成功");
    		}catch(Exception e){
    			result.put("code",1);
    			result.put("msg","失败");
    		}
    		return result;
    	}
    
    
    
    	/**
    	 * @param path1 图片原路径
    	 * @param path2 裁剪后存储的路径
    	 * @param x x轴
    	 * @param y y轴
    	 * @param w
    	 * @param h
    	 */
    	public static void CutImage(String path1,String path2,int x,int y,int w,int h){
    		FileInputStream fileInputStream=null;
    		ImageInputStream iis=null;
    
    		try {
    			//读取图片文件,建立文件输入流
    			fileInputStream=new FileInputStream(path1);
    			//创建图片的文件流 迭代器
    			Iterator it = ImageIO.getImageReadersByFormatName("jpg");
    			ImageReader reader=it.next();
    			//获取图片流 建立文图 文件流
    			iis=ImageIO.createImageInputStream(fileInputStream);
    			//获取图片默认参数
    			reader.setInput(iis, true);
    			ImageReadParam param=reader.getDefaultReadParam();
    			//定义裁剪区域
    			Rectangle rect=new Rectangle(x,y,w,h);
    			param.setSourceRegion(rect);
    			BufferedImage bi=reader.read(0,param);
    			ImageIO.write(bi, "jpg", new File(path2));
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println("裁剪失败");
    		}finally{
    			try {
    				if(fileInputStream!=null){
    					fileInputStream.close();
    				}
    				if(iis!=null){
    					iis.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    
    		}
    	}

    以上就是我这个功能的代码,我只是自己留下以后可能用得到,还少一部分代码,有时间我就加上。

    补上之前上传头像那块的Java代码,之前少弄了那个上传文件的代码,很关键哈哈:

    String filetype=".zip|.xls|.xlsx|.doc|.docx|.ppt|.pptx|.jpg|.jpeg|.png|.gif|.rar|.txt|.csv|.pdf|.wps|.dps";
        public boolean isfiletype(String suffix){
    
            return filetype.contains(suffix.toLowerCase());
        }
        @RequestMapping("/uploadfiles.html")
        @ResponseBody
        public String uploadfile( @RequestParam String fid,HttpServletRequest request, HttpServletResponse response) {
            Map m = new HashMap();
            try {
    //取得上传的文件
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                multipartRequest.getParameter("");
                MultipartFile  file =  multipartRequest.getFile(fid);
                //取得上传的文件
    
            // response.setContentType("text/html");
            // response.setCharacterEncoding("UTF-8");
    
                    //得到文件名称
                    String realFileName = file.getOriginalFilename();
                    String suffix = realFileName.substring(realFileName.lastIndexOf("."));
                    //判断文件类型是否可用和文件类型
                    if (!isfiletype(suffix)) {
                        m.put("success", false);/** 结果类型 */
                        m.put("message", "你上传的文件类型不正确!");/** 返回消息 */
                        m.put("errorCode", 1);/** 错误代码 */
                        return RenderUtil.renderJson(CodeConstants.CODE_SUCCESS, m);
                    }
                    String fileRealPath = request.getSession().getServletContext().getRealPath("/") + "/upload/";
                    UUID uuid = UUID.randomUUID();
                    String randomName = UUID.randomUUID().toString() + suffix;
                    //判断文件夹是否存在
                    File targerFile = new File(fileRealPath);
                    //判断是否存在目录
                    if (!targerFile.exists()) {
                        targerFile.mkdirs();
                    }
                    //保存文件
                    File uploadFile = new File(fileRealPath + randomName);
    
                    FileCopyUtils.copy(file.getBytes(), uploadFile);
                DecimalFormat df=new DecimalFormat("######0.00");
                long i=file.getSize();
                    String s=null;
                    if(i<1024){
                        s=i+"B";
                    }else if(i>1024&&i<1048576){
                        s=df.format((double)i/1024)+"KB";
                    }else {
                        s=df.format((double)i/1048576)+"MB";
                    }
    
                    //配置文件实体信息
                    m.put("success", true);/** 结果类型 */
                    m.put("message", "文件上传成功!");/** 返回消息 */
                    m.put("filepath", "/upload/" + randomName);/** 返回消息 */
                    m.put("filesize",s);/** 返回消息 */
                    m.put("errorCode", 0);/** 错误代码 */
                    return RenderUtil.renderJson(CodeConstants.CODE_SUCCESS, m);
    
            } catch (IOException e) {
                m.put("success", false);/** 结果类型 */
                m.put("message", "上传失败!");/** 返回消息 */
                m.put("errorCode",1);/** 错误代码 */
                return  RenderUtil.renderJson(CodeConstants.CODE_SUCCESS, m);
            }
        }
    这些代码不是自己原创,有网上找的有自己项目里写好的,分享在这就是为了自己以后找着方便,而且也方便大家。

    你可能感兴趣的:(微信公众号)