五十二、微信小程序云开发中的云存储
@Author:Runsen
暑假很長,明年就是找工作的時候了。這個時候必須比之前還要拼命。
百翻無下,努力就是我的代言詞。今天,正式進入云存儲的學習。云存儲這個概念在之前學習的時候沒有注意到。
下面是官方文檔鏈接
官方文檔
文章目錄
- 上傳圖片
- 展示圖片
- 下載圖片
上傳圖片
首先,我去查看上傳圖片的API。
上傳圖片的官方文檔
wx.chooseImage(Object object):從本地相冊選擇圖片或使用相機拍照。
下面我在index.wxml中給定,上傳圖片的按鈕
<button bindtap="onloadimage">上傳圖片</button>然后在index.js中的實現onloadimage的方法,下圖是官方的示例。
在小程序中的云開發上傳圖片的API接口,官方文檔如下;https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/storage/uploadFile/client.uploadFile.html
展示圖片
在這里定義了一個image的空列表,當點擊按鈕時,通過調用云函數中的login,然后將返回的data保存到云數據庫中。
下載圖片
對于下載圖片,通過定義data-fileid綁定fileID,然后通過fileID: event.target.dataset.fileid拿到fileID,下面就是一個wx.cloud.downloadFile云函數下載圖片的方法,具體查看官方文檔
下面是全部代碼
index.wxml代碼
<button bindtap="onloadimage">上傳圖片</button> <button bindtap="getimage">展示圖片</button> <block wx:for="{{image}}"><image src="{{item.fileID}}"></image><button size="mini" data-fileid="{{item.fileID}}" bindtap="downloadimage">下載圖片</button> </block>index.js代碼
//index.js const app = getApp() const db = wx.cloud.database()Page({data: {image: []},onloadimage:function(){wx.chooseImage({count: 1,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success (res) {// tempFilePath可以作為img標簽的src屬性顯示圖片const tempFilePaths = res.tempFilePaths;console.log(tempFilePaths[0]);wx.cloud.uploadFile({cloudPath: new Date().getTime() + ".png",filePath: tempFilePaths[0], // 文件路徑success: res => {// get resource IDconsole.log(res.fileID)db.collection("image").add({data:{fileID:res.fileID,}}).then(res=>{console.log(res)}).catch(err=>{console.log(err)})},fail: err => {// handle error}})},})},// 展示圖片getimage:function(){wx.cloud.callFunction({name:"login",}).then(res=>{db.collection("image").where({_openid:res.result.openid}).get().then(res2=>{console.log(res2)this.setData({image: res2.data})})})},// 下載圖片downloadimage:function(event){wx.cloud.downloadFile({fileID: event.target.dataset.fileid, // 文件 IDsuccess: res => {// 返回臨時文件路徑console.log(res.tempFilePath)// 保存圖片到手機相冊wx.saveImageToPhotosAlbum({filePath: res.tempFilePath,success(res){wx.showToast({title: '保存成功',})}})},fail: console.error})} })上傳圖片
下載圖片
總結
以上是生活随笔為你收集整理的五十二、微信小程序云开发中的云存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 五十一、微信小程序云开发中的云函数
- 下一篇: 支付宝添加银行卡怎么添不上