1、页面内先写好上传按钮
<view style="width:80%;text-align:center;margin:0 auto;background:#ccc" class="upimgstyle" bindtap="uploadImgView">上传</view>
<!-- 下面这个是为了在页面展示图片 可以不加 -->
<view class="imgView">
<view class="imgs" wx:if="{{imglist.length>0}}" wx:for="{{imglist}}" wx:key='index'><image style="width:500rpx;height:500rpx;" src="{{item}}"></image></view>
</view>
2、js 上传事件
data: {
imglist:[] // 页面图片展示的 可以不加
},
//上传图片按钮
uploadImgView:function(e){
let _t=this
wx.chooseImage({
count: 2, // 最多上传几个 默认9
sizeType: ['original','compressed'], // 原图/压缩图
sourceType: ['album', 'camera'], // 相册/相机
success: (res) => {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
console.log('上传',res)
// res.tempFilePaths[0]
_t.setData({imglist:res.tempFilePaths})//页面展示用,可以不加
for(let i=0; i<res.tempFilePaths.length; i++ ){
//图片上传云服务
wx.cloud.uploadFile({
cloudPath:Date.parse(new Date())+i+'.png',//图片上传时名字会覆盖,所以这边用时间戳和索引值拼的
//cloudPath:'uploadimage/'+Date.parse(new Date())+index+'.png',//前面加上 文件夹名字/test.png 图片就会上传到指定的文件夹下,否则按上面的会传到根目录下
filePath:res.tempFilePaths[i], // 文件路径
success: res => {
console.log('上传云',res)
console.log(res.fileID)
},
fail: err => {
console.log('上传云err',err)
// handle error
}
})
//这个可以页面展示或者传给自己接口的后台如果要base64的话 转成base64 可以不加
//_t.zhuanImage(res.tempFilePaths[i],i)
}
}
});
},
//将图片转成 base64 用于页面展示
zhuanImage:function(imgsrc,index){
let _t=this
let list=_t.data.imglist
wx.getFileSystemManager().readFile({
filePath:imgsrc, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
console.log('111',res)
// console.log('res---',res)
let img_flow = 'data:image/png;base64,' + res.data;
// console.log('img_flow---',img_flow)
list.push(img_flow)
_t.setData({imglist:list})
}
});
},
运行效果
默认云控制台什么都没有
当点击上传按钮时
wx.chooseImage返回如下信息
上传云返回的结果
此时云端自动创建了文件夹(cloudPath:'uploadimage/'+自己起的图片名字+'.png',)
如果这个地方不写文件夹名字,图片就会存在根目录下 cloudPath:自己起的图片名字+'.png',