小程序云开发(二)使用云开发接口函数实现云空间文件的上传、下载和删除操作

 

//app.js
App({
  onLaunch: function () {
    
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // 此处请填入环境 ID, 环境 ID 可打开云控制台查看
        env: 'luna-7gm1d64198b1c778',
        traceUser: true,
      })
    }

    this.globalData = {}

  }
})
<!--pages/index/index.wxml-->

<view class='box'>
  <view class='title'>文件上传/下载</view>
  <view class="Hcontainer">
    <button type='primary' bindtap="doUpload">上传图片</button>
    <button type='primary' wx:if="{{uploadSuccess}}" bindtap="doDownload">下载图片</button>
  </view>
  <view wx:if="{{uploadSuccess}}" class="list">
    <text class="list-title">上传成功</text>
    <view class="list-item">
      <text>文件 ID:{{fileID}}</text>
    </view>
    <view class="list-item">
      <text>云文件路径:{{cloudPath}}</text>
    </view>
  </view>
  <view wx:if='{{downloadSuccess}}' class="list">
    <text class="list-title">下载成功</text>
    <text class='list-text'>点击缩略图可预览图片</text>
    <view class='image-container'>
      <image src="{{downloadedFilePath}}" mode="aspectFit" bindtap="previewImg"></image>
    </view>
  </view>
</view>



<button type='primary' wx:if="{{uploadSuccess}}" bindtap="doDownload">下载图片</button>条件渲染,显示的条件是uploadSuccess这个变量为true,上传图片成功显示此button组件,绑定的事件是doDownload

<image src="{{downloadedFilePath}}" mode="aspectFit" bindtap="previewImg"></image>image组件,文件源绑定的是downloadedFilePath这个变量,即下载文件的临时路径,绑定的点击事件是previewImg,点击图片的时候调用previewImg函数
/* pages/index/index.wxss */

.Hcontainer {
  margin: 100rpx 0rpx 50rpx;
  padding: 0 50rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.opButton {
  color: white;
  background-color: #0f0;
  border-radius: 10px;
}

.list {
  margin-top: 40rpx;
  width: 100%;
  padding: 0 40rpx;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-left: none;
  border-right: none;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  box-sizing: border-box;
}

.list-title {
  margin: 20rpx;
  color: black;
  font-size: 28px;
  font-style: bold;
  display: block;
}

.list-item {
  width: 100%;
  padding: 10rpx;
  font-size: 16px;
  color: #007aff;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.list-text {
  color: red;
  font-size: 12px;
  display: block;
}

.image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-container image {
  max-width: 30%;
  max-height: 10vh;
  margin-top: 20rpx;
  border: 1px solid #e0e0e0;
}
// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileID: '', // 上传文件的ID
    cloudPath: '', // 上传文件的云端路径
    imagePath: '', // 上传图片的本地临时路径
    downloadedFilePath: '', // 图片下载后的本地临时路径
    uploadSuccess: false, // 文件是否上传成功的标记
    downloadSuccess: false // 文件是否下载成功的标记
  },
  // 图片上传事件函数
  doUpload: function() {
    var that = this;
    const fileID = this.data.fileID;//取到页面变量fileID的值保存到常量fileID
    if (fileID != '') { // 如果之前上传了图片(fileID不为空)则删除之
      wx.cloud.deleteFile({
        fileList: [fileID] // 要删除的文件ID的数组
      })
    }
    // 选择图片
    wx.chooseImage({ // 调用接口选择图片
      count: 1, // 图片数量
      sizeType: ['compressed'], // 尺寸类型
      sourceType: ['album', 'camera'], // 图片来源
      success: function(res) { // 调用成功时的回调函数
        wx.showLoading({ // 显示加载提示框
          title: '上传中',
        })
        const filePath = res.tempFilePaths[0] // 保存上传文件的临时路径
        console.log("filePath:", filePath)
        // 上传图片
        const cloudPath = 'img' + Date.now() + filePath.match(/.[^.]+?$/)[0]
        wx.cloud.uploadFile({ // 调用接口上传文件
          cloudPath, // 文件的云端路径
          filePath, // 文件的本地临时路径
          success: res => { // 调用成功时的回调函数
            console.log('[上传文件] 成功:', res)// 上传成功返回的res变量中就会有文件的id
            that.setData({ // 设置页面绑定数据
              uploadSuccess: true,
              downloadSuccess: false,
              fileID: res.fileID,// 文件的id,保存到本地的页面变量ileID
              cloudPath: cloudPath,
              imagePath: filePath,
              downloadedFilePath: ''
            })
          },
          fail: e => { // 调用失败时的回调函数
            console.error('[上传文件] 失败:', e);
            that.setData({ // 设置页面绑定数据
              uploadSuccess: false,
              fileID: '',
              cloudPath: '',
              imagePath: ''
            })
            wx.showToast({ // 显示消息提示框
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => { // 调用完成时的回调函数
            wx.hideLoading() // 隐藏加载提示框
          }
        })
      },
      fail: e => { // 调用失败时的回调函数
        console.error(e)//选择图片失败,仅做错误记录
      }
    })
  },
  // 图片下载事件函数
  doDownload: function() {
    var that = this;
    wx.showLoading({ // 显示加载提示框
      title: '下载中',
    })
    wx.cloud.downloadFile({ // 调用接口下载文件
      fileID: that.data.fileID, // 云端文件ID,要下载的文件ID,之前上传的时候,上传图片的id,已经保存到了页面变量fileID中,这里赋值给所需的参数
      success: res => { // 调用成功时的回调函数
        console.log("下载文件成功: ", res)// 下载成功返回的res变量中就有下载文件的临时路径
        that.setData({ // 设置页面绑定数据
          downloadSuccess: true,
          downloadedFilePath: res.tempFilePath//把下载文件的临时路径设置给页面变量downloadedFilePath,同时把downloadSuccess设置为true,然后使用setData方法进行页面数据的更新
        })
        wx: wx.showModal({ // 显示模态对话框
          title: '文件下载成功',
          content: '文件路径:' + that.data.downloadedFilePath,
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#0000ff',
        })
      },
      fail: err => { // 调用失败时的回调函数
        that.setData({ // 设置页面绑定数据
          downloadSuccess: false,
          downloadedFilePath: ''
        })
      },
      complete: () => { // 调用完成时的回调函数
        wx.hideLoading() // 隐藏加载提示框
      }
    })
  },
  // 图片预览事件函数
  previewImg: function() {
    wx.previewImage({ // 调用接口预览图片
      current: '', // 当前显示图片的http链接
      urls: [this.data.downloadedFilePath] // 需要预览的图片url的数组,this.data.downloadedFilePath下载的图片文件的临时路径
    })
  }
})
    if (fileID != '') { // 如果之前上传了图片(fileID不为空)则删除之
      wx.cloud.deleteFile({
        fileList: [fileID] // 要删除的文件ID的数组
      })
    }
如果不是空字符串,就说明之前上传了一次图片,调用deleteFile接口,把文件删除,参数是待删除的文件列表,只有一个文件,就是当前文件的fileID,这样做的目的,避免一次反复的上传文件,造成云端文件太多,如果之前已经上传了一次文件,就先将文件删除,再进行后面的上传
success: function(res) { // 调用成功时的回调函数
        wx.showLoading({ // 显示加载提示框
          title: '上传中',
        })
        const filePath = res.tempFilePaths[0] // 保存上传文件的临时路径
        console.log("filePath:", filePath)
        // 上传图片
        const cloudPath = 'img' + Date.now() + filePath.match(/.[^.]+?$/)[0]
        wx.cloud.uploadFile({ // 调用接口上传文件
          cloudPath, // 文件的云端路径
          filePath, // 文件的本地临时路径
          success: res => { // 调用成功时的回调函数
            console.log('[上传文件] 成功:', res)
            that.setData({ // 设置页面绑定数据
              uploadSuccess: true,
              downloadSuccess: false,
              fileID: res.fileID,
              cloudPath: cloudPath,
              imagePath: filePath,
              downloadedFilePath: ''
            })
          },
          fail: e => { // 调用失败时的回调函数
            console.error('[上传文件] 失败:', e);
            that.setData({ // 设置页面绑定数据
              uploadSuccess: false,
              fileID: '',
              cloudPath: '',
              imagePath: ''
            })
            wx.showToast({ // 显示消息提示框
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => { // 调用完成时的回调函数
            wx.hideLoading() // 隐藏加载提示框
          }
        })
      },
选择图片成功的话,返回参数res,res中就有选择的图片文件的临时路径,是一个数组,只选择1个,取其中下标值为0的就可以,保存在filePath常量中
之后上传选择的图片,上传之前,先构造一下在云端的文件路径,把文件在云端命名为一个由img三个字母开头+当前时间相关的数字+原来文件的拓展名的新的文件名,因为没有指定路径,所以这个文件在云端就是在根目录下
 

一、小程序云开发的存储功能

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

二、文件上传、下载、删除接口

  1、文件上传接口wx.cloud.uploadFile(Object object) 

    参数object的属性主要包括cloudPath、 filePath以及回调函数。

     cloudPath是文件的云存储路径。

     filePath是要上传的文件资源的路径。

    在回调函数success中,可以获得调用成功时 的返回参数,包括云文件的fileID和HTTP状 态码statusCode。

  2、文件下载接口wx.cloud.downloadFile(Object object)

    参数object的属性主要包括fileID和回调函数。

    fileID是云文件 ID。

    在回调函数success中,可以获得调用成功 时的返回参数 , 包 括 临 时 文 件 路 径 tempFilePath和HTTP状态码statusCode。

  3、文件删除接口wx.cloud.deleteFile(Object object)

    参数object的属性主要包括fileList和回调函数。

    fileList是云文件 ID 字符串数组。

    在回调函数success中,可以获得调用成功 时的返回参数fileList。这是一个删除结果 列表,列表中的每个元素都是一个对象, 对象的属性包括云文件的fileID、状态码 status和错误消息errMsg。

原文地址:https://www.cnblogs.com/suitcases/p/14841770.html