在Vue中调用微信上传图片功能

5 篇文章 0 订阅
2 篇文章 0 订阅

在Vue中调用微信上传图片功能

效果

说明

  • 后台微信参数获取(略)

上传流程

  1. 点击图片控件位置,进行选择图片
  2. 选择相机拍照或图库上传
  3. 上传完成显示到图片控件

开发流程

  1. 引入weixin插件
  2. 页面初始化时获取微信认证参数【参数后台服务提供】,获取本页地址
  3. 图片点击事件进行图片上传、图片回显操作
  4. 后台从微信服务器中下载上传的图片到自己的服务器

代码

  • vue中引入weixin插件

     

    npm install weixin-js-sdk --save
    
  • 页面图片控件

     

    <img :src="imgURL" style="width: 90px;height: 90px" @click="addVipImage()"/>
    
  • 数据

     

    data() {
      return {
        URL: '',
        serverPrefix: "后台获取微信参数的接口地址?url=",
        imgURL: '',
      }
    },
    
  • 挂载方法中获取本页地址及初始化微信参数

     

    mounted: function () {
      //获取本页地址
      this.URL = location.href.split("#")[0];
      //获取微信参数
      this.wxConfig();
    },
    

     

    wxConfig() {
        let self = this;
        let url = this.serverPrefix + this.URL;
        this.$ajax.post(url).then(
          function (data) {
            if (data.status == 200) {
              var jsondata = data.data;
              //【注-------------这里根据自己后台的返回的数据做相应的调整---------------】
              if (jsondata.code === 200) {
                wx.config({
                  // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                  debug: false,
                  // 必填,公众号的唯一标识
                  appId: jsondata.model.appId,
                  // 必填,生成签名的时间戳
                  timestamp: "" + jsondata.model.timestamp,
                  // 必填,生成签名的随机串
                  nonceStr: jsondata.model.nonceStr,
                  // 必填,签名
                  signature: jsondata.model.signature,
                  // 必填,需要使用的JS接口列表
                  jsApiList: [
                    "chooseImage", //拍照或从手机相册中选图接口
                    "previewImage", //预览图片接口
                    "uploadImage", //上传图片接口
                    "downloadImage" //下载图片接口
                  ]
                });
              }
            }
          },
          function (data) {
            var jsondata = data.body;
          }
        );
      },
    
  • 点击图片上传事件

     

      addVipImage: function () {
        let self = this;
        wx.chooseImage({
          count: 1, //张数, 默认9
          sizeType: ["compressed"], //建议压缩图
          sourceType: ["album", "camera"], // 来源是相册、相机
          success: function (res) {
            self.imgURL = res.localIds[0];
            self.uploadToWeixinServer(res.localIds[0]);
          }
        });
      },
    

     

      uploadToWeixinServer(localId) {
        let self = this;
        wx.uploadImage({
          localId: localId,
          isShowProgressTips: 1, // 默认为1,显示进度提示
          success: function (res) {
            //res.serverId 返回图片的微信服务器端ID
            self.add_vip.serverId = res.serverId;
          }
        });
      },
    
  • 后台从微信服务器上下载上传的图片

     

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class WeixinImageUtils {
        public static String saveImageToDisk(String accessToken,String mediaId, String picName, String picPath) throws Exception {
            InputStream inputStream = getInputStream(accessToken, mediaId);
            // 循环取出流中的数据
            byte[] data = new byte[1024];
            int len = 0;
            FileOutputStream fileOutputStream = null;
            String filePath = picPath + picName + ".jpg";
    
            try {
                fileOutputStream = new FileOutputStream(filePath);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
            } catch (IOException e) {
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
            return filePath;
        }
    
        private static InputStream getInputStream(String accessToken, String mediaId) {
            InputStream is = null;
            String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
            try {
                URL urlGet = new URL(url);
                HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
                http.setRequestMethod("GET"); // 必须是get方式请求
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                http.setDoOutput(true);
                http.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
                System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
                http.connect();
                // 获取文件转化为byte流
                is = http.getInputStream();
            } catch (Exception e) {
            }
            return is;
        }
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值