微信小程序上传图片

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

微信小程序上传图片

Vue酱   2022-06-28 我要评论

//wxml <button class='button' bingtap="uploadSomeMsg">上传</button>    
          <view class="uploadImgBox">
            <view class='smallImgBox'>
              <block wx:for="{{img_arr}}" wx:key="index">
                <view class='logoinfo'>
                  <image class='logoinfo' mode="aspectFill" src='{{item}}' data-index="{{index}}" bindtap="previewImg"
                    bindlongpress="deleteImg" name="headimage" ></image>
                </view>
              </block>
              <image bindtap='getLocalityImg' class='moreImg' src="../../images/uploadPictures.png">
              </image>
            </view>
            <view>
          </view> 
</view>
//wxss
.uploadImgBox {
  margin: 30rpx 0;
}

.logoinfo {
  height: 180rpx;
  width: 180rpx;
  margin: 10rpx ;
}

.smallImgBox {
  display: grid;
  grid-template-columns: repeat(3,1fr);
  grid-template-rows: repeat(2,180rpx);
  grid-gap:20rpx 10rpx;
}

.moreImg {
  border-radius: 10rpx;
  height: 180rpx;
  width: 180rpx;
  margin: 20rpx ;
}.button{  
 height: 90rpx;  
 width: 270rpx;  
 font-size: 38rpx;  
 background-color: rgba(146, 163, 45, 0.288);  
 font-weight: 600;  
 color: white;
 } 
 button::after {
  border: none;
} 
//js
Page({
  data: {
    img_arr: [], //储存照片的数组
  },

//https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html  微信小程序上传文件api
  //上传图片到服务器 
  uploadSomeMsg() {
    var that = this
    var adds = that.data.img_arr;
    for (let i = 0; i < this.data.img_arr.length; i += 1) {
      wx.uploadFile({
        url:'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
        filePath: that.data.img_arr[i],
        name: 'content',
        formData: {
          'user': adds
        },
        success: function (res) {
          console.log(res, "上传图片啦")
          if (res) {
            wx.showToast({
              title: '已提交发布!',
              duration: 3000
            });
          }
        }
      })
    }
  },

  //从本地获取照片 
  getLocalityImg() {
    let that = this;
    if (this.data.img_arr.length < 5) {
      wx.chooseImage({
        count: 5 - that.data.img_arr.length, //上传图片的数量 当之前上传了部分图片时 ,总数 - 已上传数 = 剩余数   (限制上传的数量)
        sizeType: ['original', 'compressed'],  //可以指定原图或压缩图,默认二者都有
        sourceType: ['album', 'camera'],        //指定图片来源是相机还是相册,默认二者都有
     success(res) {
          console.log(res, "---------上传的图片")

          const tempFiles = res.tempFiles //包含图片大小的数组

          let answer = tempFiles.every(item => {   //限制上传图片大小为2M,所有图片少于2M才能上传
            return item.size <= 2000000
          })
    
          if (answer) {
            that.setData({
              img_arr: that.data.img_arr.concat(res.tempFilePaths),
            })
          }else{
                  wx.showToast({
                title:'上传图片不能大于2M!',
                icon:'none'    
            })
          }

        }
      })

    } else {
      wx.showToast({  //超过图片张数限制提示
        title: '最多上传五张图片',
        icon: 'none',
        duration: 2000
      })

    }
  },

  //删除照片功能与预览照片功能 
  deleteImg(e) {
    let that = this;
    let img_arr = that.data.img_arr;
    let index = e.currentTarget.dataset.index;  //获取长按删除图片的index
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗?',
      success(res) {
        if (res.confirm) {
          // console.log('点击确定了');
          img_arr.splice(index, 1);
        } else if (res.cancel) {
          // console.log('点击取消了');
          return false;
        }
        that.setData({
          img_arr: img_arr
        });
      }
    })
  },

  //预览图片
  previewImg(e) {
    let index = e.currentTarget.dataset.index;
    let img_arr = this.data.img_arr;
    wx.previewImage({
      current: img_arr[index],
      urls: img_arr
    })
  },


})

#转换成base64格式

//1__转换本地上传图片

//如果需要上传base64格式图片到后端,可以在上传图片时可以这样转换,其它的和普通接口上传数据一样
          //转换结果
        let data=wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64") 
//`data:image/png;base64,${data}`
//上传时只需要在转换结果前加一个: `data:image/png;base64,${data}`   ,就是完整的图片数据啦

  //2__转换服务器网络图片为base64
    images.forEach(url => {
          let newUrl = `https://dx.showweb.net/upload${url}` //需拼上前缀才能下载网络图片

        this.imageToBase(newUrl).then((res)=>{
          this.data.img_arr.push(res)
          this.setData({
            img_arr:this.data.img_arr
          })
          })

        })


  imageToBase(img) {
   return new Promise((resolve, reject)=>{
      wx.downloadFile({ //先下载图片
        url: img,
        success(res) {
          if (res.statusCode === 200) {
            wx.playVoice({
              filePath: res.tempFilePath //选择图片返回的相对路径
            })
            resolve(res.tempFilePath)
          }
        }
      })
    })
  },

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们