<checkbox-group bindchange="setDelArr">
<view class="wp">
<view wx:for="{{urlArr}}" wx:key="index">
<image src="{{item.tempFileURL}}" bindtap="previewImage" data-url="{{item.tempFileURL}}" bindlongpress="changeBol"></image>
<checkbox value="{{item.fileID}}" wx:if="{{bol}}"></checkbox>
</view>
</view>
</checkbox-group>
<button type="primary" bindtap="uploadImg">上传图片</button>
<button type="primary" bindtap="delImg" wx:if="{{bol}}">删除</button>
// pages/actfile/actfile.js
const db = wx.cloud.database();
Page({
data: {
bol:false,
urlArr:[], //
viewUrls:[], //预览数组
delArr:[], //要删除的文件的fileid
},
//选择图片
setDelArr(ev){
console.log(ev.detail.value);
this.setData({
delArr:ev.detail.value
});
},
//点击删除按钮
delImg(){
wx.showModal({
title:'确认删除',
content:'你确定要删除吗?',
success:res=>{
if(res.confirm){ //确定删除
wx.cloud.deleteFile({
fileList: this.data.delArr
}).then(res => {
// handle success
if(res.fileList.length>0){ //删除成功
//删除数据表中的数据
this.data.delArr.forEach( async item=>{
await db.collection('fileids').where({
fileid:item
}).remove();
});
//重置
this.setData({
delArr:[],
urlArr:[],
bol:false
});
this.getFileid();
}
});
}
}
});
},
changeBol(){
this.setData({
bol:true
});
return false;
},
//预览图片
previewImage(ev){
let url = ev.currentTarget.dataset.url;
wx.previewImage({
current: url, // 当前显示图片的http链接
urls:this.data.viewUrls // 需要预览的图片http链接列表
});
},
//上传图片
uploadImg(){
wx.chooseImage({
count:9,
}).then(res=>{
//输出上传文件的临时存路径
// console.log(res.tempFilePaths[0]);
res.tempFilePaths.forEach(async item=>{
//获取上传文件的文件名
let a = item.split('/');
let fname = a[a.length-1];
//使用 wx.cloud.uploadFile 上传文件到云存储空间
const result = await wx.cloud.uploadFile({
cloudPath:fname, //存储路径
filePath:item
});
console.log(result,111);
//把fileID 存入数据表
this.storageData(result.fileID);
});
})
},
//获取临时网络路径
getTempFileURL(fileID){
wx.cloud.getTempFileURL({
//fileList 文件的fileid数组,一个fileid表示一个文件
fileList: fileID,
success: res => {
// fileList 是一个有如下结构的对象数组
// [{
// fileID: 'cloud://xxx.png', // 文件 ID
// tempFileURL: '', // 临时文件网络链接
// maxAge: 120 * 60 * 1000, // 有效期
// }]
console.log(res.fileList)
this.setData({
urlArr:res.fileList,
viewUrls: res.fileList.map(item=>item.tempFileURL)
});
},
fail: console.error
});
},
//把提交图片的fileID存储到数据表中
async storageData(fileID){
//把fileid存到表中
let res = await db.collection('fileids').add({
data:{
fileid:fileID
}
});
//存储成功以后,把表中的所有fileid获取到
if(res._id){
this.getFileid();
}
},
//获取数据表中的fileid
getFileid(){
let arr=[];
db.collection('fileids').get().then(res=>{
console.log(res.data);
//遍历获取data中的fileid
arr = res.data.map(item=>item.fileid);
//获取临时网络路径
this.getTempFileURL(arr);
});
},
onLoad: function (options) {
this.getFileid();
},