微信小程序:雲開發·初探三(文件操作)

We are the champion. We’ll keep on fighting till the end.


雲開發·文件上傳

  • 上傳文件

在小程序端可調用 wx.cloud.uploadFile 方法進行上傳:

wx.cloud.uploadFile({
  cloudPath: 'example.png', // 上傳至雲端的路徑
  filePath: '', // 小程序臨時文件路徑
  success: res => {
    // 返回文件 ID
    console.log(res.fileID)
  },
  fail: console.error
})

上傳成功後會獲得文件唯一標識符,即文件 ID,後續操作都基於文件 ID 而不是 URL。

  • 下載文件

可以根據文件 ID 下載文件,用戶僅可下載其有訪問權限的文件:

wx.cloud.downloadFile({
  fileID: '', // 文件 ID
  success: res => {
    // 返回臨時文件路徑
    console.log(res.tempFilePath)
  },
  fail: console.error
})
  • 刪除文件
    可以通過 wx.cloud.deleteFile 刪除文件:
wx.cloud.deleteFile({
  fileList: ['a7xzcb'],
  success: res => {
    // handle success
    console.log(res.fileList)
  },
  fail: console.error
})
  • 換取臨時鏈接
    可以根據文件 ID 換取臨時文件網絡鏈接,文件鏈接有有效期爲兩個小時:
wx.cloud.getTempFileURL({
  fileList: ['cloud://xxx.png'],
  success: res => {
    // fileList 是一個有如下結構的對象數組
    // [{
    //    fileID: 'cloud://xxx.png', // 文件 ID
    //    tempFileURL: '', // 臨時文件網絡鏈接
    //    maxAge: 120 * 60 * 1000, // 有效期
    // }]
    console.log(res.fileList)
  },
  fail: console.error
})
  • 代碼示例:
//index.js
const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    // requestResult: '',      imagePath:'http://tmp/wx0263defb02461a81.o6zAJs8UG5md089i-lEg2pvHbysc.ocF6poZa1XQLf8a15cd6a694541b22121078b6e6142b.gif',
  },

  onLoad: function() {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 獲取用戶信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接調用 getUserInfo 獲取頭像暱稱,不會彈框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // 調用雲函數
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[雲函數] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[雲函數] [login] 調用失敗', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  //測試getInfo雲函數
  getInfoClick: function () {
    wx.cloud.callFunction({
      name: 'getInfo',
      complete: res => {
        console.log(res)
      }
    })
  },

  // 上傳圖片
  doUpload: function () {
    var that = this;
    // 選擇圖片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: '上傳中',
        })

        const filePath = res.tempFilePaths[0]

        // 上傳圖片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        console.log(cloudPath);
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上傳文件] 成功:', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            that.setData({
              fileID: res.fileID,
              cloudPath: cloudPath,
              imagePath: filePath,
            })

            console.log(that.data);
            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上傳文件] 失敗:', e)
            wx.showToast({
              icon: 'none',
              title: '上傳失敗',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

  //下載圖片
  downloadFile:function(){
    var that = this
    wx.cloud.downloadFile({
      fileID: 'cloud://had-development-697e49.ddea-had-development-697e49/my-image.gif', // 文件 ID
      success: res => {
        // 返回臨時文件路徑
        console.log(res)

      },
      fail: console.error
    })
  },

  getTempFileURL:function(){
    var that = this;
    wx.cloud.getTempFileURL({
      fileList: ['cloud://had-development-697e49.ddea-had-development-697e49/my-image.gif'],
      success: res => {
        // fileList 是一個有如下結構的對象數組
        // [{
        //    fileID: 'cloud://xxx.png', // 文件 ID
        //    tempFileURL: '', // 臨時文件網絡鏈接
        //    maxAge: 120 * 60 * 1000, // 有效期
        // }]
        console.log(res.fileList)
        that.setData({
          fileID: res.fileList[0].fileID,
          imagePath: res.fileList[0].tempFileURL,
        })
      },
      fail: console.error
    })
  }

})

這裏寫圖片描述

https://github.com/Goddreamwt/HAD/commit/434cd7f5e1a07e72afa4275fa43320c000c3cc55

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章