uniapp判断图片是否真实有效

在utils.js公共方法

//uniapp判断图片是否真实有效
function checkImage(path, timeout = 3000) {
    if (!path || typeof path !== 'string' || path.trim() === '') {
        return Promise.resolve(false)
    }
    
    path = path.trim()
    
    // base64 直接返回 true
    if (path.startsWith('data:image')) {
        return Promise.resolve(true)
    }
    
    // 统一使用 uni.getImageInfo 检测
    return new Promise((resolve) => {
        const timer = setTimeout(() => {
            resolve(false)
        }, timeout)
        
        uni.getImageInfo({
            src: path,
            success: () => {
                clearTimeout(timer)
                resolve(true)
            },
            fail: () => {
                clearTimeout(timer)
                resolve(false)
            }
        })
    })
}
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
export default {
    checkImage,
    defaultAvatarUrl
}

 

async getList() {
  uni.showLoading({
    title: '加载中...'
  });
  let obj = {}
  let url = ''
  if(this.showingIndex1 == 1){
    //入驻排行榜
    url = this.$httpUrl.rankingList
  }else{
    //分享下单排行榜
    url = this.$httpUrl.orderRankingList
  }
  await this.$api.request(url, 'GET',obj,async res => {
    if(res.code === -1){
      this.$utils.logBackIn(res.code)
    }else if (res.code === 1) {
      let info = res.data
      // 这里不能用forEach,不支持同步
      // info.forEach(async (item,index)=>{
      for(let item of info){
        //无效图片赋值默认图片
        let flag = await this.$utils.checkImage(item.avatar)
        // console.log(flag)
        let goodsLogo = flag ? item.avatar : this.$utils.defaultAvatarUrl;
        item.url = goodsLogo
        item.name = item.nickname
        if(this.showingIndex1 == 1){
          //入驻排行榜
          item.num = item.product_recommender_count
        }else{
          //分享下单排行榜
          item.num = item.order_count
        }
      }
      // })
      this.$nextTick(() => {
        this.tableList = info;

        if(this.tableList.length==0){
          this.empty = false
        }else{
          this.empty = true
          if(this.max == this.to){
            this.loadMoreText = "没有更多数据了!"
          }else if(this.max < this.to){
            this.loadMoreText = "加载中..."
          }
          this.showLoadMore = true
        }
      })
      uni.hideLoading();
    }else{
      uni.showToast({
        title: res.msg,
        icon: 'none',
        duration: 2000
      });
    }
  })
},

 

posted @ 2026-06-17 11:10  峪野  阅读(5)  评论(0)    收藏  举报