微信小程序云开发学习笔记(三)云存储

一、小程序云存储简介

云开发提供了一块存储空间,提供了上传文件到云端、带权限管理的云端下载能力,开发者可以在小程序端和云函数端通过 API 使用云存储功能。

在小程序端可以分别调用 wx.cloud.uploadFilewx.cloud.downloadFile 完成上传和下载云文件操作

二、选择并上传图片

使用的API:

  1. wx.chooseImage

  2. wx.cloud.uploadFile

实现步骤

1. 初始化云环境

在app.js中指定云开发环境,其中env是你自己指定的环境ID

app.js中的代码如下:

App({
  onLaunch: function () {
    wx.cloud.init({
      env: "cloud-learning-i44qm"
    })
  }
})

2. 新建一个pageuploadImg用于测试

3. uploadImg.wxml中,

<button bindtap="handleTap">上传</button>
<image src="{{URL}}"></image>

4. uploadImg.js中(版本一)

Page({
  data:{
    URL:''
  },

  handleTap() {
    let that = this
    console.log("点击了上传按钮")
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log("选择成功", res)
        that.upload(res.tempFilePaths[0])
      }
    })
    
    
  },

  upload(imgUrl) {
    wx.cloud.uploadFile({
      cloudPath: new Date().getTime() +'.png',    //防止文件名重复,使用时间戳
      filePath: imgUrl, // 文件路径
      success: res => {
        // get resource ID
        console.log("上传成功",res)
        this.setData({
          URL: res.fileID
        })
      },
      fail: err => {
        // handle error
      }
    })
  }
})

5. uploadImg.js中(版本二)

Page({
  data: {
    imgURL:''
  },
  selectAndUpload() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        console.log('choose successfully',res)
        wx.cloud.uploadFile({
          cloudPath: new Date().getTime() + '.png',
          filePath: res.tempFilePaths[0], // 文件路径
          success: function (res) {
            console.log('upload successfully', res)
            that.setData({
              imgURL: res.fileID
            })
          },
          fail(res) {
            console.log('upload failed', res)
          }
        })
      },
      fail(res) {
        console.log('choose failed', res)
      }
    })
  },
})

6. 查看控制台和模拟器,我们发现如下输出:

在这里插入图片描述
在这里插入图片描述

三、选择并上传视频

使用的API:

  1. wx.chooseVideo

  2. wx.cloud.uploadFile

实现步骤

同上,把图片API相关代码换为如下即可

wx.chooseVideo({
  sourceType: ['album','camera'],
  maxDuration: 600,
  camera: 'back',
  success(res) {
    console.log(res.tempFilePath)
  }
})

四、选择并上传多媒体文件(图片+视频)

使用的API:

  1. wx.chooseMedia

  2. wx.cloud.uploadFile

实现步骤

同上,把图片API相关代码换为如下即可

wx.chooseMedia({
  count: 9,
  mediaType: ['image','video'],
  sourceType: ['album', 'camera'],
  maxDuration: 300,
  camera: 'back',
  success(res) {
    console.log(res.tempFiles.tempFilePath)
    console.log(res.tempFiles.size)
  }
})

五、实现类似朋友圈效果

效果

编辑并share页面如下:
在这里插入图片描述
点击分享以后,跳转到以前share过的朋友圈页面,点击左上角可以返回,如下:在这里插入图片描述

说明

本demo会用到微信小程序的云开发功能,包括云数据库,云存储

实现步骤

1. 云开发环境的初始化

详见:https://blog.csdn.net/Panda325/article/details/108117775

2. 新建page

新建两个pagesharepyqshare用于编辑文案并选择配图,pyq用于查看以前发过的朋友圈
app.jsonpages字段如下:

"pages": [
    "pages/share/share",
    "pages/pyq/pyq"
  ],

在这里插入图片描述

3. share页面

share页面从上到下依次是:多行输入框 textarea,选择图片的按钮 button,分享按钮 button
share.wxml如下:

<textarea placeholder="输入您的文案" bindblur="bindTextAreaBlur"
   value="{{details}}" class='text'> </textarea>
<input>\n\n</input>
<button bindtap="seleteAndUploadPicture">
<image src='https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2444066247,3899866315&fm=26&gp=0.jpg'></image>
</button>
<input>\n\n</input>
<button bindtap="share">分享</button>

share.js如下:

const DB = wx.cloud.database().collection("pyq")
Page({
 data: {
   details: '',
   imgURL: ''
 },
 bindTextAreaBlur: function (e) {
   console.log(e.detail.value);
   var that = this;
   that.setData({
     details: e.detail.value
   });
 },
 seleteAndUploadPicture() {
   let that = this
   wx.chooseImage({
     count: 1,
     sizeType: ['original', 'compressed'],
     sourceType: ['album', 'camera'],
     success: res => {
       console.log('choose successfully', res)
       that.setData({
         imgURL: res.tempFilePaths[0]
       })
     },
     fail(res) {
       console.log('choose failed', res)
     }
   })
 },
 share() {
   console.log('调用share的方法')
   let that = this
   wx.cloud.uploadFile({
     cloudPath: new Date().getTime() + '.png',
     filePath: this.data.imgURL, // 文件路径
     success: function (res) {
       console.log('upload successfully', res)
       that.setData({
         imgURL: res.fileID
       })
     },
     fail(res) {
       console.log('upload failed', res)
     }
   })
   DB.add({
     data: {
       descption: this.data.details,
       imgURL: this.data.imgURL
     },
     success(res) {
       console.log("share成功", res)
       wx.navigateTo({
         url: "../../pages/pyq/pyq"
       })
       wx.showToast({
         title: '成功',
         icon: 'success',
         duration: 2000
       })
     },
     fail(res) {
       console.log("share失败", res)
     }
   })
 }
})

share.wxss如下:

.text{
 /* height: 100rpx;
 line-height: 100rpx; */
 width: 100%;
 font-size: 60rpx;
 background-color: #bfa;
}

4. pyq页面

pyq.wxml如下:

<view wx:for="{{array}}">
<view>{{index}} : {{item.descption}}</view>
<image src="{{item.imgURL}}"></image>
<view>\n</view>
</view>

pyq.js如下:

const DB = wx.cloud.database().collection("pyq")
Page({
 data: {
   array: []
 },
 onLoad() {
   let that = this
   DB.get({
     success(res) {
       that.setData({
         array: res.data
       })
       for (let i = 0; i < res.data.length; i++) {
         console.log(res.data[i].descption)
         console.log(res.data[i].imgURL)
       }
     }
   })
 }
})

我的邮箱:1125806272@qq.com
我的博客:http://9pshr3.coding-pages.com/
https://zhenglin-li.github.io/
我的csdn:https://me.csdn.net/Panda325
我的简书:https://www.jianshu.com/u/e2d945027d3f
我的今日头条:https://www.toutiao.com/c/user/4004188138/#mid=1592553312231438
我的博客园:https://www.cnblogs.com/zhenglin-li/

posted @ 2020-08-20 10:42  嗯这  阅读(1648)  评论(0编辑  收藏  举报