微信小程序实现文件( 原生 && vant组件 )云存储

505 阅读3分钟

一. 前言

我们知道,云开发控制台更多的是对项目中的初始文件的操作管理,例如项目的Logo图片可以通过云开发控制台提起上传到云端。项目在执行的过程中也会涉及文件的操作,例如用户上传图片的操作,这时就需要用到云开发存储API。

二. 原生小程序文件云存储

1.原生小程序实现云存储

  • 在小程序端可以分别调用 wx.cloud.uploadFile 和 wx.cloud.downloadFile 完成上传和下载云文件操作。
  • 定义上传按钮,调用wx.chooseImage()方法,触发文件选择器,选择文件后返回以下数据
 // 上传文件
  uploadFile(){
    // 从本地相册上传图片或使用相机拍照
    wx.chooseImage({
      count: 0,
      sizeType: [],
      sourceType: [],
      success: (result) => {
        console.log(result);
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  • 返回数据

image.png

  • 在获取文件路径成功的回调中,调用wx.cloud.uploadFile()方法
  • 定义云路径cloudPath,定义临时路径filePath
  // 上传文件
  uploadFile() {
    // 从本地相册上传图片或使用相机拍照
    wx.chooseImage({
      count: 0,
      sizeType: [],
      sourceType: [],
      success: (result) => {
        console.log(result);
        // 上传文件至数据库
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          // "imgs/"为自定义文件夹名(如果未找到,则自动生成)
          // 此处以时间戳为文件名,防止重复
          // 通过截取获取文件格式
          cloudPath: "imgs/" + new Date().getTime() + result.tempFilePaths[0].substr(result.tempFilePaths[0].length - 4),
          // 指定要上传的文件的小程序临时文件路径
          filePath: result.tempFilePaths[0],
          //成功回调
          success: res => {
            console.log('上传成功', res)
          },
        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  • 成功后返回的fileID可用于页面渲染

image.png

  • 查看刷新存储库查看文件是否存在

image.png

image.png

2.使用vant组件实现云存储

  • 下载vant,引入组件,使用Uploader文件上传插件(原生小程序如何使用vant在vant官网有详细教程,有兴趣的可以了解一下,在此不做过多叙述)
  • upload-icon图标_____max-count最大上传数量_____multiple是否开启图片多选
  • file-list为一个对象数组,用于展示相关,详情可了解vant中Uploader文件上传相关文档
  • accept为接受的文件类型, 可选值为all media image file video
  • bind:after-read 文件读取完成后执行的事件,通过回调参数可以获取当前读取的文件
<!-- van-uploader组件 -->
<van-uploader 
upload-icon="plus" 
max-count="{{9}}"
multiple="{{true}}" 
file-list="{{ fileList }}" 
accept="all" 
bind:after-read="afterRead"> 
</van-uploader>
<!-- 确认上传  -->
<van-button type="primary" block bindclick="uploadBtn">上传</van-button>
<!-- 展示图片  -->
<view class="imgs">
  <image wx:for="{{newfileList}}" wx:key="index" src="{{item.fileID}}" mode="aspectFill"> </image>
</view>
</view>

  • 点击组件时选择文件后获取文件信息,存储到全局变量中
// 上传文件
  afterRead(e) {
    // 对选择的文件数据进行循环
    e.detail.file.forEach(item => {
      // 添加新的数组中
      this.data.fileList.push(item)
    })
    this.setData({
      fileList: this.data.fileList
    })
  },
  • 点击上传文件按钮,循环发送文件上传请求,通过Promise.all()合并请求,完成后清空展示做出提示
// 确认上传
  async uploadBtn() {
    // 判断点击上传文件时,是否存在文件资源
    if (this.data.fileList.length == 0) {
      // 没有则返回相应提示
      return wx.showToast({
        title: '请选择文件',
        icon: 'none'
      });
    }
    // 定义空数组
    let arr = []
    // 循环调用uploadFile上传数据库
    this.data.fileList.forEach(item => {
      let data = wx.cloud.uploadFile({
        // 此处可以使用item.name,包含文件名与格式
        cloudPath: "imgs/" + item.name,
        //云存储临时路径
        filePath: item.url
      })
      // 循环时添加返回Promise对象至数组中
      arr.push(data)
    })
    // Promise.all( )能够一次并行处理多个 promise,并且只返回一个 promise 实例,resolve 回调的结果是一个数组
    // 通过Promise.all合并请求
    let result = await Promise.all(arr)
    // 完成后存储结果清除展示数据
    this.setData({
      newfileList: result,
      fileList: []
    })
    //成功提示
    wx.showToast({
      title: '上传成功',
    })
  },