小程序雲開發(四):雲數據庫的文件操作之上傳頭像圖片,獲取雲圖片

一,上傳文件

在這裏插入圖片描述

//cloudPath: 'comp_img/' + new Date().getTime() + parseInt(Math.random() * 10) + avatar.match(/\.[^.]+?$/)[0],//.match(/\.[^.]+?$/)[0]=圖片類型後綴,,new Date().getTime()=時間戳,,parseInt(Math.random() * 10)=10以內的隨機整數
wx.cloud.uploadFile({
      cloudPath: 'comp_img/' + app.globalData.openid,//頭像類的唯一圖片,就用openid命名,再上傳就會覆蓋原來的,避免殘留!'comp_img/'是文件夾名稱!
      filePath: avatar, // 文件路徑
      success: res => {
        console.log('[上傳文件] 成功:', res)
        //雲函
        wx.cloud.callFunction({
          name: 'updateUserInfo',
          data: {
            comp_img: res.fileID,
          },
          complete: lete => {
            console.log('updateUserInfo=' + JSON.stringify(lete))
          }
        })
        that.setData({
          comp_img: avatar
        })

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

根據圖片ID取回本地路徑

let openid = app.globalData.openid;
    const db = wx.cloud.database();
    const Users = db.collection('Users');
    Users.where({ _openid: openid }).get({
      success: function (res) {
        console.log(res)
        that.checkED(arrSex,res.data[0].comp_sex);
        that.setData({
          arrSex: arrSex,
          comp_name: res.data[0].comp_name,
          comp_sex: res.data[0].comp_sex,
          comp_email: res.data[0].comp_email,
          comp_mobile: res.data[0].comp_mobile,
          //comp_work_pcp: res.data[0].citykey,
          address: res.data[0].comp_work_address,
        })
        wx.cloud.downloadFile({
          fileID: res.data[0].comp_img, // 文件 ID
          success: res => {
            // 返回臨時文件路徑
            that.setData({comp_img:res.tempFilePath})
          },
          fail: console.error
        })
      },
      fail: function (err) {
        console.error('err:', err)
      },
      complete: function (ok) {

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