微信端图片上传方式2

调用微信接口JS-SDK方式

前台代码:

1 <div class="link_cameraB">
2             <img class="link_camera" data-up="img" src="img/all/link_camera.png" id="infoByOCR" οnclick="photo(1)"   >点击时调用方法photo(type)
3 </div>

JS代码

  1  function link_init() {
  2     CompareVersion();
  3     var wxopenid = getcookie("wxopenid");
  4     var access_code = GetQueryString("code");
  5     if (wxopenid == "" || wxopenid == null || wxopenid == "null") {
  6         var fromurl = location.href;
  7         if (access_code == null) {
  8             var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
  9                     + getAppId()
 10                     + "&redirect_uri="
 11                     + encodeURIComponent(fromurl)
 12                     + "&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect";
 13             location.href = url;
 14         } else {
 15             $.ajax({
 16                 type : "get",
 17                 url : "/suyi/open/getOpenId.shtml",
 18                 async : false,
 19                 cache : false,
 20                 data : {
 21                     code : access_code
 22                 },
 23                 dataType : "json",
 24                 success : function(result) {
 25                     if (result != null && result.result == 1) {
 26                         addcookie("wxopenid", result.openId, 360000);
 27                         $("#openId").val(result.openId);
 28                         init();
 29                     } else {
 30                         location.href = fromurl;
 31                     }
 32                 }
 33             });
 34         }
 35     } else {
 36         $("#openId").val(wxopenid);
 37         init();
 38     }//用于微信openid的获取 
39 var link = location.href; 40 $.ajax({ 41 type : "get", 42 url : "/suyi/open/getSign.shtml", 43 async : false, 44 cache : false, 45 data : { 46 link : link 47 }, 48 dataType : "json", 49 success : function(result) { 50 if (result != null && result.result == 1) { 51 wx.config({ 52 debug : false, 53 appId : result.appId, 54 timestamp : result.sign.timestamp, 55 nonceStr : result.sign.nonceStr, 56 signature : result.sign.signature, 57 jsApiList : [ "checkJsApi", "onMenuShareTimeline", 58 "onMenuShareAppMessage", "onMenuShareQQ", 59 "onMenuShareWeibo", "onMenuShareQZone", 60 "hideMenuItems", "showMenuItems", 61 "hideAllNonBaseMenuItem", "showAllNonBaseMenuItem", 62 "translateVoice", "startRecord", "stopRecord", 63 "onVoiceRecordEnd", "playVoice", "onVoicePlayEnd", 64 "pauseVoice", "stopVoice", "uploadVoice", 65 "downloadVoice", "chooseImage", "previewImage", 66 "uploadImage", "downloadImage", "getNetworkType", 67 "openLocation", "getLocation", "hideOptionMenu", 68 "showOptionMenu", "closeWindow", "scanQRCode", 69 "chooseWXPay", "openProductSpecificView", 70 "addCard", "chooseCard", "openCard" ] 71 }); 72 } else { 73 alert("\u9875\u9762\u52a0\u8f7d\u5931\u8d25"); 74 } 75 }, 76 error : function(data) { 77 alert("\u8fde\u63a5\u5931\u8d25\uff01"); 78 } 79 }); 80 }  //获得微信接口一些功能的授权 81 82 function init() { 83 // fastclick,使移动端点击没有延迟 84 FastClick.attach(document.body); 85 86 } 91 function photo(type) { 92 var images = { 93 localId : [], 94 serverId : [] 95 }; 96 wx.chooseImage({ 97 count : 1, 98 sizeType : [ "original", "compressed" ], 99 sourceType : [ "album", "camera" ], 100 success : function(res) { 101 var localIds = res.localIds; 102 images.localId = res.localIds; 103 var i = 0, length = images.localId.length; 104 function upload() { 105 wx.uploadImage({ 106 localId : images.localId[i].toString(), 107 success : function(res) { 108 i++; 109 images.serverId.push(res.serverId); 110 var indata = { 111 "media_id" : res.serverId, 112 114 }; 115 $.post("/suyi/open/getPhoto.shtml", indata, function( 116 data) { 117 if (data.result == 0) { 118 alert("\u63d0\u4ea4\u5931\u8d25"); 119 } else if(data.result==1) { 120 var path = data.path //获得传回来的地址 134 } 137 138 }, "json"); 139 if (i < length) { 140 upload(); 141 } 142 }, 143 fail : function(res) { 144 alert(JSON.stringify(res)); 145 } 146 }); 147 } 148 upload(); 149 } 150 }); 151 }

后台代码:

// TODO 微信端上传图片
    @RequestMapping(value = "/getPhoto", method = RequestMethod.POST)
    @ResponseBody
    public Object getPhoto(String media_id,String ocr,HttpServletRequest request,
            HttpServletResponse response) throws NoSuchAlgorithmException {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="
                + WeixinUtil.getAccessToken() + "&media_id=" + media_id;
        InputStream inputStream = null;
        String saveFileName = null;
        PrintWriter writer = null;
        JSONObject obj = new JSONObject();
        try {
            writer = response.getWriter();
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url
                    .openConnection();
            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.connect();
            // 将返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
            byte[] data = new byte[1024];
            int len = 0;
            FileOutputStream fileOutputStream = null;
            saveFileName = System.currentTimeMillis()
                    + RandomStringUtils.random(6, true, true) + ".jpg";
            Date date = new Date();
            String datePath = format.format(date);
            String upload = "D:\\suyi\\photo\\" + datePath + "\\";
            String path = upload + saveFileName;
            File dir = new File(upload);
            if (!dir.exists()) {
                FileUtils.forceMkdir(dir);
            }
            try {
                fileOutputStream = new FileOutputStream(path);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            String Path="/suyi/showImage?imgId=" + datePath + "_"
                    + saveFileName;
            obj.put("result", 1);
            obj.put("path", Path);
            
        } catch (Exception e) {
            e.printStackTrace();
            obj.put("result", 0);
        } finally {
            writer.print(obj);
            if (writer != null) {
                writer.close();
            }
        }
        return null;
    }

 

转载于:https://www.cnblogs.com/future-eye/p/8267845.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值