微信小程序:云开发·初探三(文件操作)

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

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