微信小程序——云开发实现图片上传到云存储并实时预览当前上传的图片

1.配置云开发

打开云开发
在这里插入图片描述
拷贝环境ID
在这里插入图片描述
在全局app.js中配置
在这里插入图片描述

2.界面编写

编写一个前端界面

<view>
    <button type="primary" bindtap="uploadimg">点我上传</button>
</view>

绑定事件函数

 uploadimg(){
        wx.chooseImage({
            count: 1,
            success (res) {
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths
              console.log(tempFilePaths)
              
        wx.cloud.uploadFile({
            cloudPath: 'img/example.png', // 上传至云端的路径
            filePath: tempFilePaths[0], // 小程序临时文件路径
            success: res => {
              // 返回文件 ID
              console.log(res.fileID)
            },
            fail: console.error
          })
            }
          })
    },

注:这里面用到了两个API,wx.chooseImage用来选择一张或几张图片,wx.cloud.uploadFile用来上传选中的文件
在这里插入图片描述

在这里插入图片描述

测试:
此时我们选中一张图片后就可以上传到云存储的对应文件夹内了
在这里插入图片描述
在存储里面点击刷新就出现了我配置的img文件夹了
在这里插入图片描述
里面正是我刚刚上传的图片
在这里插入图片描述
接下来要做的就是把选择后的图片显示在界面上

3.把选中的图片显示在界面上

前端页面优化

<view>
    <button type="primary" bindtap="uploadimg">点我上传</button>
    <text>图片预览:</text>
    <image src="{{selctedimg}}"></image>
</view>

js代码优化

data: {
        selctedimg:'',
    },
    uploadimg(){
        //声明this,这里面嵌套的太多,里面拿不到this
        let _that=this

        wx.chooseImage({
            count: 1,
            success (res) {
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths
              //获取到每张图片的名字
              const fileName=res.tempFilePaths[0].slice(11)
           // console.log(res.tempFilePaths[0])
            //console.log(res.tempFilePaths[0].slice(11))
              
        wx.cloud.uploadFile({
        //这里拼接的字符串也可以使用模板字面量
        //cloudPath: `img/${fileName}.png`, 
            cloudPath: 'img/'+fileName+'.png', // 上传至云端的路径
            filePath: tempFilePaths[0], // 小程序临时文件路径
            success: res => {
              // 返回文件 ID
              console.log(res.fileID)

              _that.setData({
                  selctedimg:res.fileID
              })
            },
            fail: console.error
          })
            }
          })
    },

测试:
现在就实现了上传那张图片就可以实时预览那张图片了!在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4.手机上测试

当然也可以在手机上测试该上传功能
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 22
    点赞
  • 92
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值