- 云开发控制台的数据库里创建好集合articles
- index.wxml:
//这里处理为一个轮播图,实时轮播出artcles数据库中的图片
<swiper indicator-dots="{{indicatorDots}}"
autoplay="{{autoplay}}" interval="{{interval}}"
duration="{{duration}}">
<block wx:for="{{imgUrls}}">
<swiper-item>
<image src="{{item}}" class="slide-image" width="100%" height="100%" />
</swiper-item>
</block>
</swiper>
<!-- 上传图片 -->
<view class="uploader">
<view class="uploader-text" bindtap="doUpload">
<text>上传图片</text>
</view>
<view class="uploader-container" wx:if="{{imgUrl}}">
<image class="uploader-image" src="{{imgUrl}}" mode="aspectFit" bindtap="previewImg"></image>
</view>
</view>
- index.js:
data:{
userInfo: {},
indicatorDots: true,
autoplay: true,
interval: 5000,
duration: 1000,
imgUrls: [],
openid: ''
},
onload: function(){
const that = this
const db = wx.cloud.database()
let _arr = []
db.collection('articles').get({
success: res => {
var arr = res.data;
for (var i = 0; i < arr.length; i++) {
_arr.push(
arr[i].bigImg
)
}
this.setData({
imgUrls: _arr
})
console.log('[数据库] [查询记录] 成功: ', res.data)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查询记录失败'
})
console.error('[数据库] [查询记录] 失败:', err)
}
})
},
doUpload: function () {
let _this = this;
wx.chooseImage({
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
wx.showLoading({
title: '上传中',
})
const filePath = res.tempFilePaths[0]
console.log(filePath )
const name = Math.random() * 1000000;
console.log(name)
const cloudPath = name + filePath.match(/\.[^.]+?$/)[0]
wx.cloud.uploadFile({
cloudPath,
filePath,
success: res => {
let fileID = res.fileID;
console.log('[上传文件] 成功:', fileID)
const db = wx.cloud.database();
db.collection("articles").add({
data: {
bigImg: fileID
},
success: function () {
_this.data.imgUrls.push(fileID);
_this.setData({ imgUrls: _this.data.imgUrls
});
wx.showToast({
title: '图片存储成功',
'icon': 'none',
duration: 3000
}),
console.log("255");
},
fail: function () {
wx.showToast({
title: '图片存储失败',
'icon': 'none',
duration: 3000
})
}
});
},
fail: e => {
console.error('[上传文件] 失败:', e)
},
complete: () => {
wx.hideLoading()
}
})
},
fail: e => {
console.error(e)
}
})
},