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

编程知识 更新时间:2023-04-04 03:11:37

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.手机上测试

当然也可以在手机上测试该上传功能




更多推荐

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

本文发布于:2023-04-04 03:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/0e3d8bdbc425ad425a65a6fbeea7f2b7.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图片上传   实时   上传   程序   图片

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 40914文章数
  • 14阅读数
  • 0评论数