1. 程式人生 > >微信小程式:雲開發·初探三(檔案操作)

微信小程式:雲開發·初探三(檔案操作)

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
    })
  }

})

這裡寫圖片描述