1. 程式人生 > 實用技巧 >雲端儲存之上傳圖片和展示圖片(小程式雲開發)

雲端儲存之上傳圖片和展示圖片(小程式雲開發)

1.雲端儲存介紹

2.demo程式碼(上傳圖片/檔案)

cloud.wxml

<view>雲端儲存</view>
<button bindtap="upload">上傳圖片</button>

cloud.js

// miniprogram/pages/cloud/cloud.js
const db = wx.cloud.database();//初始化資料庫
Page({

  /**
   * 頁面的初始資料
   */
  data: {

  },

  // 上傳圖片
  upload() {
    // 1.選擇圖片  ,官方文件api
    // https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
    wx.chooseImage({
      count: 1,//當前圖片選擇個數, 小程式最多支援一下選擇9張
      sizeType: ['original', 'compressed'], //['原始檔','壓縮檔案']
      sourceType: ['album', 'camera'],//檔案來源  ['相簿','攝像頭牌照']
      success(res) {
        // tempFilePath可以作為img標籤的src屬性顯示圖片(圖片臨時路徑)
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths) //tempFilePaths是陣列
        // 官方api   https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/storage/api.html
        wx.cloud.uploadFile({
          //cloudPath: 'example.png', // 上傳至雲端的路徑
        //圖片名字 先用時間戳代替了,看自己喜好         cloudPath: new Date().getTime()+'.png',
          filePath: tempFilePaths[0], // 小程式臨時檔案路徑
          success: res => {
            // 返回檔案 ID
            console.log(res.fileID)
            db.collection('image').add({
              data: {
                fileID: res.fileID
              }
            }).then(res=>{
              console.log(res)
            }).catch(err=>{
              console.error(err)
            })
          },
          fail: console.error
        })
      }
    })
  }

})

至此上傳圖片成功啦!

資料庫裡:

雲端儲存裡:

3.圖片/檔案 獲取展示

<view style="line-height:200rpx">雲端儲存</view>
<button bindtap="getFile">圖片展示</button>

<block wx:for="{{images}}" wx:key="index">
  <image src="{{item.fileID}}"></image>
</block>
// 獲取圖片 並且展示  先獲取當前使用者登入的openid再去對應的  拿資料
  getFile() {
    wx.cloud.callFunction({
      name: 'login'
    }).then(res => {
      db.collection('image').where({
        _openid:res.result.openid
      }).get().then(res2=>{
        console.log(res2)
        this.setData({
          images: res2.data
        })
      })
    })
  },
其中wx.cloud.callFunction({
      name: 'login'
    })

login雲函式自帶的,直接拿來用,也可以自己寫, 寫完記得右鍵部署

效果:

4.圖片/檔案 下載

<block wx:for="{{images}}" wx:key="index">
  <image mode="aspectFill" src="{{item.fileID}}"></image>
  <button size="mini" data-fileid="{{item.fileID}}" bindtap="downloadFile">下載圖片</button>
</block>
//下載圖片/檔案
  downloadFile(e) {
    // console.log(e.target.dataset.fileid)
    wx.cloud.downloadFile({
      fileID: e.target.dataset.fileid, // 檔案 ID
      success: res => {
        // 返回臨時檔案路徑
        console.log(res.tempFilePath)

        // 官方api儲存圖片到相簿https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.saveImageToPhotosAlbum.html
        // 儲存圖片到手機相簿
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '儲存到手機成功',
            })
          },
          fail(err) {
            console.log(err)
              wx.showModal({
                title: '提示',
                content: '需要您授權儲存相簿',
                showCancel: true,//是否顯示取消按鈕
                success: res => {
                  if (res.confirm) {
                    console.log('使用者點選確定')
                    wx.openSetting({
                      success: res2 => {
                        if (res2.authSetting['scope.writePhotosAlbum']) {
                          wx.showModal({
                            title: '提示',
                            content: '獲取許可權成功,再次點選圖片即可儲存',
                          })
                        }
                      },
                      fail: err2 => {
                        console.log(err2)
                      }
                    })
                  } else if (res.cancel) {
                    console.log('使用者點選取消')
                  }
                }
              })
          }
        })
      },
      fail: console.error
    })
  },

我這邊的設計, 使用者拒絕授權相簿, 再次點選 彈出 再次去授權, 比較人性