微信小程序雲開發學習筆記(三)雲存儲


一、小程序雲存儲簡介

雲開發提供了一塊存儲空間,提供了上傳文件到雲端、帶權限管理的雲端下載能力,開發者可以在小程序端和雲函數端通過 API 使用雲存儲功能。

在小程序端可以分別調用 wx.cloud.uploadFilewx.cloud.downloadFile 完成上傳和下載雲文件操作

二、選擇並上傳圖片

使用的API:

  1. wx.chooseImage

  2. wx.cloud.uploadFile

實現步驟

1. 初始化雲環境

在app.js中指定雲開發環境,其中env是你自己指定的環境ID

app.js中的代碼如下:

App({
  onLaunch: function () {
    wx.cloud.init({
      env: "cloud-learning-i44qm"
    })
  }
})

2. 新建一個pageuploadImg用於測試

3. uploadImg.wxml中,

<button bindtap="handleTap">上傳</button>
<image src="{{URL}}"></image>

4. uploadImg.js中(版本一)

Page({
  data:{
    URL:''
  },

  handleTap() {
    let that = this
    console.log("點擊了上傳按鈕")
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log("選擇成功", res)
        that.upload(res.tempFilePaths[0])
      }
    })
    
    
  },

  upload(imgUrl) {
    wx.cloud.uploadFile({
      cloudPath: new Date().getTime() +'.png',    //防止文件名重復,使用時間戳
      filePath: imgUrl, // 文件路徑
      success: res => {
        // get resource ID
        console.log("上傳成功",res)
        this.setData({
          URL: res.fileID
        })
      },
      fail: err => {
        // handle error
      }
    })
  }
})

5. uploadImg.js中(版本二)

Page({
  data: {
    imgURL:''
  },
  selectAndUpload() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        console.log('choose successfully',res)
        wx.cloud.uploadFile({
          cloudPath: new Date().getTime() + '.png',
          filePath: res.tempFilePaths[0], // 文件路徑
          success: function (res) {
            console.log('upload successfully', res)
            that.setData({
              imgURL: res.fileID
            })
          },
          fail(res) {
            console.log('upload failed', res)
          }
        })
      },
      fail(res) {
        console.log('choose failed', res)
      }
    })
  },
})

6. 查看控制台和模擬器,我們發現如下輸出:

在這里插入圖片描述
在這里插入圖片描述

三、選擇並上傳視頻

使用的API:

  1. wx.chooseVideo

  2. wx.cloud.uploadFile

實現步驟

同上,把圖片API相關代碼換為如下即可

wx.chooseVideo({
  sourceType: ['album','camera'],
  maxDuration: 600,
  camera: 'back',
  success(res) {
    console.log(res.tempFilePath)
  }
})

四、選擇並上傳多媒體文件(圖片+視頻)

使用的API:

  1. wx.chooseMedia

  2. wx.cloud.uploadFile

實現步驟

同上,把圖片API相關代碼換為如下即可

wx.chooseMedia({
  count: 9,
  mediaType: ['image','video'],
  sourceType: ['album', 'camera'],
  maxDuration: 300,
  camera: 'back',
  success(res) {
    console.log(res.tempFiles.tempFilePath)
    console.log(res.tempFiles.size)
  }
})

五、實現類似朋友圈效果

效果

編輯並share頁面如下:
在這里插入圖片描述
點擊分享以后,跳轉到以前share過的朋友圈頁面,點擊左上角可以返回,如下:在這里插入圖片描述

說明

本demo會用到微信小程序的雲開發功能,包括雲數據庫,雲存儲

實現步驟

1. 雲開發環境的初始化

詳見:https://blog.csdn.net/Panda325/article/details/108117775

2. 新建page

新建兩個pagesharepyqshare用於編輯文案並選擇配圖,pyq用於查看以前發過的朋友圈
app.jsonpages字段如下:

"pages": [
    "pages/share/share",
    "pages/pyq/pyq"
  ],

在這里插入圖片描述

3. share頁面

share頁面從上到下依次是:多行輸入框 textarea,選擇圖片的按鈕 button,分享按鈕 button
share.wxml如下:

<textarea placeholder="輸入您的文案" bindblur="bindTextAreaBlur"
   value="{{details}}" class='text'> </textarea>
<input>\n\n</input>
<button bindtap="seleteAndUploadPicture">
<image src='https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2444066247,3899866315&fm=26&gp=0.jpg'></image>
</button>
<input>\n\n</input>
<button bindtap="share">分享</button>

share.js如下:

const DB = wx.cloud.database().collection("pyq")
Page({
 data: {
   details: '',
   imgURL: ''
 },
 bindTextAreaBlur: function (e) {
   console.log(e.detail.value);
   var that = this;
   that.setData({
     details: e.detail.value
   });
 },
 seleteAndUploadPicture() {
   let that = this
   wx.chooseImage({
     count: 1,
     sizeType: ['original', 'compressed'],
     sourceType: ['album', 'camera'],
     success: res => {
       console.log('choose successfully', res)
       that.setData({
         imgURL: res.tempFilePaths[0]
       })
     },
     fail(res) {
       console.log('choose failed', res)
     }
   })
 },
 share() {
   console.log('調用share的方法')
   let that = this
   wx.cloud.uploadFile({
     cloudPath: new Date().getTime() + '.png',
     filePath: this.data.imgURL, // 文件路徑
     success: function (res) {
       console.log('upload successfully', res)
       that.setData({
         imgURL: res.fileID
       })
     },
     fail(res) {
       console.log('upload failed', res)
     }
   })
   DB.add({
     data: {
       descption: this.data.details,
       imgURL: this.data.imgURL
     },
     success(res) {
       console.log("share成功", res)
       wx.navigateTo({
         url: "../../pages/pyq/pyq"
       })
       wx.showToast({
         title: '成功',
         icon: 'success',
         duration: 2000
       })
     },
     fail(res) {
       console.log("share失敗", res)
     }
   })
 }
})

share.wxss如下:

.text{
 /* height: 100rpx;
 line-height: 100rpx; */
 width: 100%;
 font-size: 60rpx;
 background-color: #bfa;
}

4. pyq頁面

pyq.wxml如下:

<view wx:for="{{array}}">
<view>{{index}} : {{item.descption}}</view>
<image src="{{item.imgURL}}"></image>
<view>\n</view>
</view>

pyq.js如下:

const DB = wx.cloud.database().collection("pyq")
Page({
 data: {
   array: []
 },
 onLoad() {
   let that = this
   DB.get({
     success(res) {
       that.setData({
         array: res.data
       })
       for (let i = 0; i < res.data.length; i++) {
         console.log(res.data[i].descption)
         console.log(res.data[i].imgURL)
       }
     }
   })
 }
})

我的郵箱:1125806272@qq.com
我的博客:http://9pshr3.coding-pages.com/
https://zhenglin-li.github.io/
我的csdn:https://me.csdn.net/Panda325
我的簡書:https://www.jianshu.com/u/e2d945027d3f
我的今日頭條:https://www.toutiao.com/c/user/4004188138/#mid=1592553312231438
我的博客園:https://www.cnblogs.com/zhenglin-li/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM