五十二、微信小程序云开发中的云存储
@Author:Runsen
暑假很長(zhǎng),明年就是找工作的時(shí)候了。這個(gè)時(shí)候必須比之前還要拼命。
百翻無(wú)下,努力就是我的代言詞。今天,正式進(jìn)入云存儲(chǔ)的學(xué)習(xí)。云存儲(chǔ)這個(gè)概念在之前學(xué)習(xí)的時(shí)候沒(méi)有注意到。
下面是官方文檔鏈接
官方文檔
文章目錄
- 上傳圖片
- 展示圖片
- 下載圖片
上傳圖片
首先,我去查看上傳圖片的API。
上傳圖片的官方文檔
wx.chooseImage(Object object):從本地相冊(cè)選擇圖片或使用相機(jī)拍照。
下面我在index.wxml中給定,上傳圖片的按鈕
<button bindtap="onloadimage">上傳圖片</button>然后在index.js中的實(shí)現(xiàn)onloadimage的方法,下圖是官方的示例。
在小程序中的云開(kāi)發(fā)上傳圖片的API接口,官方文檔如下;https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/storage/uploadFile/client.uploadFile.html
展示圖片
在這里定義了一個(gè)image的空列表,當(dāng)點(diǎn)擊按鈕時(shí),通過(guò)調(diào)用云函數(shù)中的login,然后將返回的data保存到云數(shù)據(jù)庫(kù)中。
下載圖片
對(duì)于下載圖片,通過(guò)定義data-fileid綁定fileID,然后通過(guò)fileID: event.target.dataset.fileid拿到fileID,下面就是一個(gè)wx.cloud.downloadFile云函數(shù)下載圖片的方法,具體查看官方文檔
下面是全部代碼
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標(biāo)簽的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 => {// 返回臨時(shí)文件路徑console.log(res.tempFilePath)// 保存圖片到手機(jī)相冊(cè)wx.saveImageToPhotosAlbum({filePath: res.tempFilePath,success(res){wx.showToast({title: '保存成功',})}})},fail: console.error})} })上傳圖片
下載圖片
總結(jié)
以上是生活随笔為你收集整理的五十二、微信小程序云开发中的云存储的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 五十一、微信小程序云开发中的云函数
- 下一篇: 支付宝添加银行卡怎么添不上