将图片上传到云开发中的云存储
上传图片
wxml文件
<van-button type="primary" bindtap="afterRead">上传图片</van-button>
<van-image width="100" height="100" src="{{imgUrl}}" />
方法:
先调用 wx.chooseImage()方法,选择图片
然后调用wx.cloud.uploadFile()方法,上传图片到云存储中,并返回图片的fileID
js文件中
// 选择图片
afterRead(){
let that = this
if(that.data.imgUrl){
wx.cloud.deleteFile({
fileList: [that.data.imgUrl]
}).then(res => {
// handle success
console.log("删除成功")
}).catch(error => {
// handle error
})
}
wx.chooseImage({
count: 1,
sizeType:['original', 'compressed'],
sourceType:['album', 'camera'],
success (res) {
// tempFilePath可以作为 img 标签的 src 属性显示图片
that.uplodImage(res.tempFilePaths[0])
}
})
},
// 上传图片
uplodImage(fileURL){
wx.cloud.uploadFile({
cloudPath:new Date().getTime() + '.png',
filePath:fileURL,
success:res=>{
this.setData({
imgUrl:res.fileID
})
},
fail:err=>{
console.log("失败");
}
})
},
删除图片
调用wx.cloud.deleteFile()方法,传入图片的fileID
wx.cloud.deleteFile({
fileList: [that.data.imgUrl]
}).then(res => {
// handle success
console.log("删除成功")
}).catch(error => {
// handle error
})