1.雲存儲介紹
2.demo代碼(上傳圖片/文件)
cloud.wxml
<view>雲存儲</view> <button bindtap="upload">上傳圖片</button>
cloud.js
// miniprogram/pages/cloud/cloud.js
const db = wx.cloud.database();//初始化數據庫
Page({
/**
* 頁面的初始數據
*/
data: {
},
// 上傳圖片
upload() {
// 1.選擇圖片 ,官方文檔api
// https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
wx.chooseImage({
count: 1,//當前圖片選擇個數, 小程序最多支持一下選擇9張
sizeType: ['original', 'compressed'], //['源文件','壓縮文件']
sourceType: ['album', 'camera'],//文件來源 ['相冊','攝像頭牌照']
success(res) {
// tempFilePath可以作為img標簽的src屬性顯示圖片(圖片臨時路徑)
const tempFilePaths = res.tempFilePaths
console.log(tempFilePaths) //tempFilePaths是數組
// 官方api https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/storage/api.html
wx.cloud.uploadFile({
//cloudPath: 'example.png', // 上傳至雲端的路徑
//圖片名字 先用時間戳代替了,看自己喜好
cloudPath: new Date().getTime()+'.png',
filePath: tempFilePaths[0], // 小程序臨時文件路徑
success: res => {
// 返回文件 ID
console.log(res.fileID)
db.collection('image').add({
data: {
fileID: res.fileID
}
}).then(res=>{
console.log(res)
}).catch(err=>{
console.error(err)
})
},
fail: console.error
})
}
})
}
})
至此上傳圖片成功啦!
數據庫里:
雲存儲里:
3.圖片/文件 獲取展示
<view style="line-height:200rpx">雲存儲</view> <button bindtap="getFile">圖片展示</button> <block wx:for="{{images}}" wx:key="index"> <image src="{{item.fileID}}"></image> </block>
// 獲取圖片 並且展示 先獲取當前用戶登錄的openid再去對應的 拿數據
getFile() {
wx.cloud.callFunction({
name: 'login'
}).then(res => {
db.collection('image').where({
_openid:res.result.openid
}).get().then(res2=>{
console.log(res2)
this.setData({
images: res2.data
})
})
})
},
其中wx.cloud.callFunction({
name: 'login'
})
login雲函數自帶的,直接拿來用,也可以自己寫, 寫完記得右鍵部署
效果:
4.圖片/文件 下載
<block wx:for="{{images}}" wx:key="index"> <image mode="aspectFill" src="{{item.fileID}}"></image> <button size="mini" data-fileid="{{item.fileID}}" bindtap="downloadFile">下載圖片</button> </block>
//下載圖片/文件
downloadFile(e) {
// console.log(e.target.dataset.fileid)
wx.cloud.downloadFile({
fileID: e.target.dataset.fileid, // 文件 ID
success: res => {
// 返回臨時文件路徑
console.log(res.tempFilePath)
// 官方api保存圖片到相冊https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.saveImageToPhotosAlbum.html
// 保存圖片到手機相冊
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.showToast({
title: '保存到手機成功',
})
},
fail(err) {
console.log(err)
wx.showModal({
title: '提示',
content: '需要您授權保存相冊',
showCancel: true,//是否顯示取消按鈕
success: res => {
if (res.confirm) {
console.log('用戶點擊確定')
wx.openSetting({
success: res2 => {
if (res2.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '提示',
content: '獲取權限成功,再次點擊圖片即可保存',
})
}
},
fail: err2 => {
console.log(err2)
}
})
} else if (res.cancel) {
console.log('用戶點擊取消')
}
}
})
}
})
},
fail: console.error
})
},
我這邊的設計, 用戶拒絕授權相冊, 再次點擊 彈出 再次去授權, 比較人性