前言:
不太懂为啥vant Weapp的官方文档明明可以写全代码,却只放了一部分出来,关于云开发的案例也是写得蛮晦涩难懂的,参考了以下的文档: 云开发能力基础讲解 小程序官方文档wx.cloud.uploadFile vant Weapp官方文档Uploader 文件上传
参考了这位博主的文章 微信小程序云开发图片上传实现预览(配合vant Weapp使用)
实现效果预览:
上传成功前显示图片正在加载,上传成功才显示图片
WXML代码:
<view class="image-uploader">
<!-- 文件上传 -->
<van-uploader file-list="{{ fileList }}"
deletable="{{ true }}"
use-before-read
bind:before-read="beforeRead"
bind:after-read="afterRead"
bind:delete="deleteImg"/>
</view>
before-read:文件读取前,在回调函数中返回 false 可终止文件读取,绑定事件的同时需要将use-before-read属性设置为true after-read:文件读取完成后(不用使用wx.chooseImage,event.detail.file就是当前读取的文件
JS代码:
Page({
data: {
fileList: [],
},
beforeRead(event) {
const { file, callback } = event.detail;
callback( file.type === 'image' );
},
afterRead( event) {
const file = event.detail.file
var that = this
const fileList = that.data.fileList
fileList.push({})
fileList[ fileList.length-1 ].status='uploading'
that.setData({ fileList })
this.uploadImg( file.url )
},
uploadImg( fileURL) {
var that = this
const filePath = fileURL
const cloudPath = `${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` + filePath.match(/\.[^.]+?$/)[0]
wx.cloud.uploadFile({
cloudPath,
filePath
}).then(res => {
console.log("res.fileID", res.fileID)
const fileList = that.data.fileList
fileList[ fileList.length-1 ].url = res.fileID
fileList[ fileList.length-1 ].status='done'
that.setData({ fileList })
console.log("fileList", fileList)
wx.showToast({ title: '上传成功', icon: 'none' })
}).catch((e) => {
wx.showToast({ title: '上传失败', icon: 'none' })
const fileList = that.data.fileList
fileList[ fileList.length-1 ].status='failed'
that.setData({ fileList })
console.log(e)
});
},
deleteImg( event) {
const delIndex = event.detail.index
const fileList = that.data.fileList
var fileID = fileList[ delIndex].url
this.deleteCloudImg( fileID)
fileList.splice( delIndex, 1)
this.setData({ fileList })
},
deleteCloudImg( fileID) {
wx.cloud.deleteFile({
fileList: [ fileID],
}).then(res => {
console.log(res.fileList)
}).catch((e) => {
wx.showToast({ title: '删除失败', icon: 'none' })
console.log(e)
})
}
})
通过在数组 fileList 末尾进行添加图片信息, fileList[ fileList.length-1 ] 可以指定数组末尾,删除可以通过 删除图片的序号值 删除数组的信息fileList.splice( delIndex, 1)
|