记录 调用微信图片上传 前端上传 后端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

猜你喜欢

转载自blog.csdn.net/weixin_42612454/article/details/82781330