微信小程序云开发-上传图片到云存储、保存图片到相册

2020-03-31  本文已影响0人  月圆星繁

上传图片到云存储

  <button bindtap="upload" type="primary"> 上传图片 </button>
Page({
  upload(){
    // let that = this;
    // 选择一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        // that.uploadFile(tempFilePaths) 如果这里不是=>函数
        //则使用上面的that = this
        this.uploadFile(tempFilePaths) 
      },
    })
  },
  //上传操作
  uploadFile(filePath) {
    wx.cloud.uploadFile({
      cloudPath: (new Date()).valueOf()+'.png', // 文件名
      filePath: filePath, // 文件路径
      success: res => {
        // get resource ID
        console.log(res.fileID)
      },
      fail: err => {
        // handle error
      }
    })
  }
})

下载文件

<button bindtap="upload" type="primary"> 上传图片 </button>

<image src="{{imgUrl}}"></image>

<button bindtap="download" data-img="{{imgUrl}}" type="primary"> 下载图片 </button>
Page({
  data:{
    imgUrl:''
  },
  upload(){
    // let that = this;
    // 选择一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        // that.uploadFile(tempFilePaths) 如果这里不是=>函数使用上面的that = this
        this.uploadFile(tempFilePaths) 
      },
    })
  },
  //上传操作
  uploadFile(filePath) {
    wx.cloud.uploadFile({
      cloudPath: (new Date()).valueOf()+'.png', // 文件名
      filePath: filePath, // 文件路径
      success: res => {
        // get resource ID
        console.log(res.fileID)
        // 赋值图片
        this.setData({
          imgUrl:res.fileID
        })
      },
      fail: err => {
        // handle error
      }
    })
  },
  // 下载图片
  download(e) {
    console.log('e',e.currentTarget.dataset.img)
    let fileUrl = e.currentTarget.dataset.img
    wx.cloud.downloadFile({
      fileID: fileUrl,
      success: res => {
        console.log('下载成功', res)
        this.saveImage(res.tempFilePath)
      },
      fail: res => {
        console.log('下载失败', res)
      }
    })
  },
  // 保存图片到相册
  saveImage(imgUrl){
    wx.saveImageToPhotosAlbum({
      filePath:imgUrl,
      success(res) { },
      fail(res) {
        console.log('保存失败', res)
      }
    })
  }
})
上一篇 下一篇

猜你喜欢

热点阅读