1. 程式人生 > >記錄 呼叫微信圖片上傳 前端上傳 後端Java下載儲存(多圖上傳)

記錄 呼叫微信圖片上傳 前端上傳 後端Java下載儲存(多圖上傳)

測試頁面

<template>
    <div id="test">
        <button @click="wxchoose">微信上傳測試</button>
        <div class="img_box">
            <div v-for="(item,key) in imgList" class="img_item">
                <img class="loading" src="../../static/img/Loading.png"/>
                <div class="preview">
                    <img :src="item"/>
                </div>
                <img @click="imgRemove(key)" class="remove" src="../../static/img/process-07.png"/>
            </div>
        </div>
        <button @click="wxupload(0)">確認上傳</button>
    </div>
</template>

<script>
import wx from 'weixin-js-sdk'
export default {
    name: 'test',
    data:function() {
        return{
            imgList: [],
            idList: [],
        }
    },
    methods:{
        //---------微信上傳圖片------------
        wxchoose: function(){
            var _this = this;
            wx.chooseImage({
                count:9,//設定一次能選擇的圖片的數量 
                sizeType:['compressed'],//指定是原圖還是壓縮,預設二者都有
                sourceType:['album','camera'],//可以指定來源是相簿還是相機,預設二者都有
                success:function(res){   //微信返回了一個資源物件 
                         //res.localIds 是一個數組 儲存了使用者一次性選擇的所有圖片的資訊
                    alert(res.localIds.length);
                    for(var i = 0;i < res.localIds.length;i ++){
                        _this.imgList.push(res.localIds[i]);
                    }
    //                        ulLoadToWechat(0); //把這些圖片上傳到微信伺服器  一張一張的上傳
                }
            });
        },
        imgRemove: function(key) {
            this.imgList.splice(key,1);
//            alert(this.imgList)
        },
        wxupload: function(i) {
            var _this = this;
            var length = _this.imgList.length;
            wx.uploadImage({
                localId: _this.imgList[i], //圖片在本地的id
                success: function (res) {
                    _this.idList.push(res.serverId);
                    i ++;
                    if(i < _this.imgList.length){
                        _this.wxupload(i);
                    }else if(i == length){
                        let postData = _this.$qs.stringify({
                            imgIds: JSON.stringify(_this.idList)
                        });
                        _this.$axios.post('xxx/testUpload', postData).then(function(res){
                            alert(res.data.message);
                        }).catch(function(err){
                            alert(err);
                        });
                    }
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        }
    },
    created:function(){
        var _this = this;
          //--------微信自定義分享連結------------
        //const ua = window.navigator.userAgent.toLowerCase()
        // 如果不在微信瀏覽器內,微信分享也沒意義了對吧?這裡判斷一下
        //if (ua.indexOf('micromessenger') < 0) return false
        let postData = _this.$qs.stringify({
            pageUrl: window.location.href.split('#')[0]
        });
        _this.$axios.post('xxx/ticket',postData).then(function(res){
            var data = res.data.result;
            console.log(data);
            wx.config({
//              debug: true, // 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。
              appId: data.appid, // 必填,公眾號的唯一標識
              timestamp: data.timestamp, // 必填,生成簽名的時間戳
              nonceStr: data.noncestr, // 必填,生成簽名的隨機串
              signature: data.signature,// 必填,簽名,見附錄1
              jsApiList: [
                'translateVoice',
                'chooseImage',
                'uploadImage',
                'downloadImage'
              ] // 必填,需要使用的JS介面列表,所有JS介面列表見附錄2
            });
        }).catch(function (error) {
            console.log(error);
        });
    }
}
</script>

<style scoped>
button{
    width: 100%;
    height: 5rem;
}
.img_box{
    display: flex;
    flex-wrap: wrap;
    padding: 1rem;
    box-sizing: border-box;
}
.img_item{
    width: 30%;
    margin-right: 3%;
    position: relative;
    margin-bottom: 1rem;
}
.img_item img.loading{
    width: 100%;
    display: block;
}
.img_item .preview{
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    overflow: hidden;
}
.img_item .preview img{
    width: 100%;
    display: block;
}
.img_item .remove{
    width: 2rem;
    height: 2rem;
    display: block;
    position: absolute;
    top: -0.8rem;
    right: -0.8rem;
}
</style>
 

 

Java 程式碼

@RequestMapping("ticket")
    public Map<String,Object> ticket(HttpServletRequest request){
        AccessToken token = AccessTokenUtil.getAccessToken(WechatConfig.appId, WechatConfig.appSecret);
        if(token==null){
            return ReturnBody.returnMes(Message.succ, Result.OPERA_ERROR);
        }
        String jsapi_ticket=JsapiUtil.getJsapiTicketOfJssdk(token.getToken());
        String pageUrl = request.getParameter("pageUrl");
        String appid =WechatConfig.appId;
        Long timestamp = new Date().getTime()/1000;
        String noncestr=UUID.randomUUID().toString().replaceAll("-", "");
        String signature ="jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+pageUrl;
        signature = Sha1Util.getSha1(signature);
        System.out.println(signature);
        Map<String,Object> wechatSign = new HashMap<String,Object>();
        wechatSign.put("timestamp", timestamp);
        wechatSign.put("noncestr", noncestr);
        wechatSign.put("signature", signature);
        wechatSign.put("appid", appid);
        wechatSign.put("pageUrl", pageUrl);
        return wechatSign;
    }

 

@RequestMapping("testUpload")
    public String testUpload(HttpServletRequest request){
        String id = request.getParameter("imgIds");  // media_id集合
        if (!CommUtil.checkNull(id)) {
            return ReturnBody.returnMes(Message.error, Result.PARAMETER_ERROR);
        }
        JSONArray list = JSONArray.parseArray(id);
        AccessToken token = AccessTokenUtil.getAccessToken(WechatConfig.appId, WechatConfig.appSecret);
        List<String> image = FileUtil.downloadImage(token.getToken(), list);
        for (String string : image) {
            System.out.println(string);
        }
        return "succ";
    }

 

public static List<String> downloadImage(String accessToken,JSONArray mediaIds) {
        if(StringUtils.isBlank(accessToken) || mediaIds.size() < 1){
            return null;
        }
        List<String> pathList = new ArrayList<String>();
        String localFilePath="";
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+accessToken;
        URL url;
        BufferedInputStream bis=null;
        HttpURLConnection conn=null;
        try{
            for (Object id : mediaIds) {
                url = new URL(requestUrl + "&media_id=" + id);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setRequestMethod("GET");
                // 根據內容型別獲取副檔名
                String fileExt = conn.getHeaderField("Content-Type").split("/")[1];
                bis = new BufferedInputStream(conn.getInputStream());
                BufferedImage bi1 = ImageIO.read(bis);  
                String fileName="D://wxfile/" + UUIDTool.getUUID() + ".";//圖片儲存路徑
                FileOutputStream fos = new FileOutputStream(new File(fileName + fileExt));
                byte[] buf = new byte[8096];
                int size = 0;
                while ((size = bis.read(buf)) != -1) {
                    fos.write(buf, 0, size);
                }
                fos.close();
                localFilePath = fileName + fileExt;
                pathList.add(localFilePath);
            }
        }catch (Exception e){
            return null;
        }finally{
            try{
                bis.close();
                conn.disconnect();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return pathList;

 

傳送門:https://blog.csdn.net/sun2015_07_24/article/details/51445844