微信小程序系列——上传下载图片以及图片的展示

一、上传

wxml:

<button bindtap='upload'>上传文件</button>

js:

首先在data里添加全局变量images

data: {
  images: []
},
upload: function(){
  wx.chooseImage({
    count: 1,//数量为1个
    sizeType: ['original', 'compressed'],//选择原图或压缩后的图片
    sourceType: ['album', 'camera'],//选择访问相册、相机
    success(res) {
      // tempFilePath可以作为img标签的src属性显示图片
      const tempFilePaths = res.tempFilePaths
      wx.cloud.uploadFile({
        cloudPath: new Date().getTime() + '.png',
        filePath: tempFilePaths[0], // 文件路径是数组,取第一个
        success: res => {
          // get resource ID
          db.collection('images').add({
            data:{
              fileID: res.fileID
            }
          }).then(res => {
            console.log(res);
          }).catch(err => {
            console.log(err)
          })
        },
        fail: err => {
          // handle error
        }
      })
    }
  })
},

二、下载

wxml:

<block wx:for='{{images}}'>
  <image src='{{item.fileID}}'></image>
  <button size='mini' data-fileid='{{item.fileID}}' bindtap='downloadFile'>文件下载</button>
</block>

js:

downloadFile: function(e){
  wx.cloud.downloadFile({
    fileID: e.target.dataset.fileid,
  }).then(res => {
    // get temp file path
    //保存图片到手机相册
    wx.saveImageToPhotosAlbum({
      filePath: res.tempFilePath,
      success(res) { 
        wx.showToast({
          title: '保存成功',
        })
      }
    })
  }).catch(error => {
    // handle error
  })
},

三、展示图片

云数据库

创建一个集合,名字为:images

wxml:

<button bindtap='getFile'>文件展示</button>

<block wx:for='{{images}}'>
  <image src='{{item.fileID}}'></image>
</block>

js:

getFile: function(){
  //使用云函数获取openid
  wx.cloud.callFunction({
    name: 'login'
  }).then(res=>{
    db.collection('images').where({
      _openid: res.result.openid
    }).get().then(res2=>{
      console.log(res2);
      this.setData({
        images: res2.data
      })
    })
  })
},

四、体验小程序

       

OK, GAME OVER!

更多内容,请关注公众号:程序员高手之路

在公众号回复:小程序资源   即可免费获取以下微信小程序视频教程!

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前方一片光明

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

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

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

打赏作者

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

抵扣说明:

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

余额充值