實戰|如何使用雲開發實現照片附件上傳開發

雲開發是騰訊雲提供的雲原生一體化開發環境和工具平臺,爲開發者提供高可用、自動彈性擴縮的後端雲服務,可用於雲端一體化開發多種端應用。

開發流程

代碼引入

在當前頁面的.json 中引入組件

{
  "usingComponents": {
    "mp-uploader": "weui-miniprogram/uploader/uploader"
  }
}

代碼開發

在當前頁面.wxml中編寫上傳組件

<view class="page__bd">

    <mp-cells>

      <mp-cell>

       <mp-uploader bindfail="uploadError" bindsuccess="uploadSuccess" select="{{selectFile}}" upload="{{uplaodFile}}" files="{{files}}" max-count="4" title="附件上傳" tips="最多可上傳4張照片"></mp-uploader>

      </mp-cell>

  </mp-cells>

  </view>

bindfail 圖片上傳失敗的事件,detail爲{type, errMsg},type爲1表示圖片超過大小限制,type爲2表示選擇圖片失敗,type爲3表示圖片上傳失敗。

bindselect 圖片選擇觸發的事件,detail爲{tempFilePaths, tempFiles, contents},其中tempFiles和tempFilePaths是chooseImage返回的字段,contents表示所選的圖片的二進制Buffer列表

max-count 圖片上傳的個數限制

在當前頁面的.js中編寫

wx.cloud.init({
  env: '環境ID',
  traceUser: true,
})
 formInputChange(e) {
    const {
      field
    } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },
chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
        sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
        success: function (res) {
            // 返回選定照片的本地文件路徑列表,tempFilePath可以作爲img標籤的src屬性顯示圖片
            that.setData({
                files: that.data.files.concat(res.tempFilePaths)
            });
        }
    })
},
previewImage: function(e){
    wx.previewImage({
        current: e.currentTarget.id, // 當前顯示圖片的http鏈接
        urls: this.data.files // 需要預覽的圖片http鏈接列表
    })
},
selectFile(files) {
    console.log('files', files)
    // 返回false可以阻止某次文件上傳
},
uplaodFile(files) {
    console.log('upload files', files)
    console.log('upload files', files)
    // 文件上傳的函數,返回一個promise
    return new Promise((resolve, reject) => {
      const tempFilePaths = files.tempFilePaths;
      //上傳返回值
      const that = this;
      const object = {};
      for (var i = 0; i < tempFilePaths.length; i++) {
        let filePath = '',cloudPath = ''
        filePath = tempFilePaths[i]
        // 上傳圖片
        // cloudPath 最好按時間 遍歷的index來排序,避免文件名重複
        cloudPath = 'blog-title-image-' + new Date().getTime() + '-' + i + filePath.match(/\.[^.]+?$/)[0]

        console.log(filePath)
        console.log(cloudPath)
        const upload_task = wx.cloud.uploadFile({
          filePath, 
          cloudPath, 
          success: function(res) {
            console.log(res)
            // 可能會有好幾個200+的返回碼,表示成功
            if (res.statusCode === 200  || res.statusCode === 204 || res.statusCode === 205) {
              const url = res.fileID
              that.data.files.push(url)
              if (that.data.files.length === tempFilePaths.length) {
                object.urls = that.data.files;
                resolve(object)  //這就是判斷是不是最後一張已經上傳了,用來返回,
              }
            } else {
              reject('error')
            }
          },
          fail: function(err) {
            console.log(err)
          }, 
          conplete: () => {
            
          }
        })
      }
    })
    // 文件上傳的函數,返回一個promise
},
uploadError(e) {
    console.log('upload error', e.detail)
},
uploadSuccess(e) {
    console.log('upload success', e.detail)
}
});

屬性參考文檔:https://wechat-miniprogram.github.io/weui/docs/uploader.html

我們關聯雲開發之後,我們即可將照片上傳到數據庫中。

爲方便管理,我們可以創建CMS內容管理器。

創建CMS內容管理器

  1. 點擊雲開發->更多->內容管理 進行開通。

    2.雲開發爲大家準備了基礎版,爲大家提供了一定的免費額度。

    設置管理員賬號以及密碼,溫馨提示密碼請牢記(如果忘記密碼可以再內容管理器頁面重置密碼),設置完成後耐心等待系統初始化。

    3.根據頁面中提供的訪問地址訪問頁面登陸後,創建新的項目(這裏以花園假期爲例)

    4.我們在內容模型中創建照片上傳管理(這裏模擬情況爲僅需要用戶上傳和記錄用戶id)

    創建內容模型

    如果需要用戶上傳多張照片,在設置照片字段時候需要勾選允許用戶上傳多張照片!

    5.用戶上傳後我們可以再內容集合,相應模型中查看。

效果展示

本文由博客一文多發平臺 OpenWrite 發佈!

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