@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 ID
console.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, // 文件 ID
success: res => {
// 返回临时文件路径
console.log(res.tempFilePath)
// 保存图片到手机相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res){
wx.showToast({
title: '保存成功',
})
}
})
},
fail: console.error
})
}
})
上传图片
下载图片