关于微信公众号上传图片(VUE版)组件封装

基本的UI

《关于微信公众号上传图片(VUE版)组件封装》

因使用的是Muse-UI,对不同的画面适配并不友好,仅供参考。

第一步,使用mu-grid-list并指定cols=3,即每行显示三张。然后添加一个隐藏的Input用于处理非微信(JS-SDK)下的图片上传。
UI部分代码,其中Style 可以参考名字自己实现,主要就是修改 mu-grid-list的默认样式

<div>
  <mu-grid-list :cols="3" :cellHeight="90" >
    <mu-grid-tile v-for="img, index in images" titleBarClass="blt-hidden" :key="index">
      <img :src="img" @click="preview(img)"/>
      <div class="btm-bar">
        <mu-icon-button icon="delete" @click="remove(index)" slot="action" class="btn-opt" />
        <!--<mu-icon-button icon="zoom_in" slot="action" @click="selectedImage = img" class="btn-opt"/>-->
      </div>
    </mu-grid-tile>
    <mu-grid-tile titleBarClass="blt-hidden">
      <img :src="addPic" @click="add" v-show="notFull"/>
    </mu-grid-tile>
  </mu-grid-list>
  <input type="file" @change="onFileChange" multiple style="display: none" ref="upload" >
  <div class="blt-fullscreen" v-if="selectedImage != null"><img :src="selectedImage"  @click="selectedImage = null"><mu-icon-button icon="close" class="blt-rt" touch @click="selectedImage = null"/></div>
</div>

第二步,处理JS-SDK配置

mounted () {
  let isWeChatBroswer = Wechat.checkWeChatBroswer()
  if (isWeChatBroswer) {
    // 初始化JSConfig
    let param = {url: window.location.href} 
    this.$http.get('https://www.XXXXXX.com/jssdk/config', {params: param}).then((response) => {
      let data = response.data
      this.$wx.config({
        appId: data.appId, // 必填,公众号的唯一标识
        timestamp: data.time, // 必填,生成签名的时间戳
        nonceStr: data.randomStr, // 必填,生成签名的随机串
        signature: data.signature, // 必填,签名,见附录1
        jsApiList: ['checkJsApi', 'chooseImage',
          'previewImage', 'uploadImage', 'downloadImage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
      })
      this.ready = true
    }).catch((err) => {
      this.$toast(err.message)
      this.ready = false
    })
  }
}

第三步,处理JS-SDK下的上传,但同时,还应该注意有IOS8以上的微信里,选择的图片对应的LocalId不能直接使用img src进行显示。

// 通过localId读取对应的图片数据,同时通过【window.__wxjs_is_wkwebview】判断是否IOS微信6.5.3以上的版本,然后把localId转为Base64图片格式。另外通过$emit把读到的文件数据传给画面组件。
add (e) {
  // e.preventDefault()
  if (this.ready) {
    let currentSize = this.images.length 
    let count = this.maxSize === 0 ? 9 : this.maxSize - currentSize
    this.$wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: (res) => {
        let localIds = res.localIds // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
        localIds.forEach(li => {
          this.images.push(li)
        })
        this.readImages(currentSize)
      },
      fail: (err) => {
        this.logs.push(err)
      }
    })
  } else {
    // 普通的上传
    e.preventDefault()
    this.$refs.upload.click()
  }
},
readImages(index) {
    this.$wx.getLocalImgData({
      localId: this.images[xIndex],
      success: (res) => {
        let localData = res.localData
        if (window.__wxjs_is_wkwebview) {
          this.images.splice(xIndex, 1, localData)
          this.$emit('selected', localData)
        } else {
          this.$emit('selected', localData)
        }
        this.readImages(xIndex + 1)
      }
    })
}

页面的其他方法

onFileChange (e) {
  var files = e.target.files || e.dataTransfer.files
  if (!files.length) {
    return
  }
  this.createImage(files)
},
createImage (file) {
  if (typeof FileReader === 'undefined') {
    alert('您的浏览器不支持图片上传,请升级您的浏览器')
    return false
  }
  // var image = new Image()
  var vm = this
  var leng = file.length
  if (this.maxSize === 0 || this.images.length + leng <= this.maxSize) {
    // 继续处理
  } else {
    vm.$toast('当前选择的图片已超过最大限制')
    return
  }
  for (var i = 0; i < leng; i++) {
   // FIXME 压缩
    /* eslint-disable no-new,new-cap,no-undef */
    new html5ImgCompress(file[i], {
      done: function (file, base64) {
        vm.images.push(base64)
        this.$emit('selected', base64)
      },
      notSupport: function (file) {
        console.log('浏览器不支持!')
      }
    })
  }
  vm.$refs.upload.value = null
},
remove (index) {
  this.$emit('removed', index)
  this.images.splice(index, 1)
},
preview (img) {
  if (this.ready) {
    this.$wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: this.images // 需要预览的图片http链接列表
    })
  } else {
    this.selectedImage = img
  }
},

以上仅处理上传,如果有编辑的话,还需要其他处理

    原文作者:ccfish
    原文地址: https://segmentfault.com/a/1190000010223259
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞