小程序云开发(二) 上传图片到云服务器、上传图片并展示

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',

  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值