微信小程序云开发———云存储

发布于:2022-11-28 ⋅ 阅读:(488) ⋅ 点赞:(0)

在微信小程序的云开发平台中有一个云存储,这里可以存放它图片、音频、视频等资源,甚至还可以存储静态网页,需要使用的时候可以直接调用。

有关于云存储的安全规则可以查看官方文档:云存储安全规则 | 微信开放文档 (qq.com)

上传是需要先选择文件然后再调用上传API进行上传,但是微信小程序原本选择照片和视频的API现已经停止了维护,分别是wx.chooseImage和wx.chooseVideo。

 所以最好使用微信开发文档所说的使用wx.chooseMedia来代替这两个API

wx.chooseMedia(Object object) | 微信开放文档 (qq.com)官方文档:wx.chooseMedia(Object object) | 微信开放文档 (qq.com)

使用wx.cloud.uploadFile上传到云存储中

咱们废话不多说,直接上代码!!

js代码段:

Page({
    getlist(){
        wx.cloud.database().collection('goods')
        .get().then(res=>{
            console.log('1',res.data)
            wx.stopPullDownRefresh() //结束刷新动画
            this.setData({
                list:res.data
            })
        }).catch(err=>{
            console.log('0',err)
        })
        wx.cloud.database().collection('videos')
        .get().then(res=>{
            console.log('2',res.data)
            wx.stopPullDownRefresh() //结束刷新动画
            this.setData({
                videolist:res.data
            })
        }).catch(err=>{
            console.log('0',err)
        })
    },
    onLoad(){
        wx.startPullDownRefresh()  //启动刷新页面
        this.getlist()
    },
    choose(){
        const that = this
          wx.chooseMedia({
            count: 9,
            mediaType: ['image','video'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            camera: 'back',
            success(res) {
              console.log(res.tempFiles)
              console.log(res)
              if(res.type == "video"){
                let src = res.tempFiles[0].tempFilePath.split('tmp/')[1]
                console.log(src)
                wx.cloud.uploadFile({
                  cloudPath: 'myImage/' + new Date().getTime() + "_" +  Math.floor(Math.random()*1000) + src,
                  filePath: res.tempFiles[0].tempFilePath, // 文件路径(时间戳)
                }).then(res => {
                  that.setData({
                    videourl:res.fileID
                  })
                  console.log(that.data.videourl)
                  wx.cloud.database().collection('videos')
                  .add({
                      data:{
                        videofileID:that.data.videourl
                      }
                  }).then(res=>{
                      console.log('视频地址成功存放到数据库',res)
                  }).catch(err=>{
                      console.log('视频地址失败存放到数据库',err)
                  })
                }).catch(error => {
                  console.log('上传失败',error)
                })
              }else{
                res.tempFiles.forEach(function(item){
                  console.log(item)
                  const path = item.tempFilePath
                  let src = item.tempFilePath.split('tmp/')[1]
                  console.log(src)
                  wx.cloud.uploadFile({
                    cloudPath: 'myImage/' + new Date().getTime() + "_" +  Math.floor(Math.random()*1000) + src,
                    filePath: path, // 文件路径(时间戳)
                  }).then(res => {
                    console.log('上传成功',res.fileID)
                    wx.cloud.database().collection('goods')
                    .add({
                        data:{
                            fileID:res.fileID
                        }
                    }).then(res=>{
                        console.log('添加成功',res)
                    }).catch(err=>{
                        console.log('添加失败',err)
                    })
                  }).catch(error => {
                    console.log('上传失败',error)
                  })
                })
              }
            }
          })
      },
    //   监听用户下拉事件
    onPullDownRefresh:function(){
        console.log('下拉事件监听')
        // 自带刷新动画
        this.getlist()
    }
})

创建两个运输库分别存储上传的image和video不同的id

wxml:

   <view class="first" >
        <view wx:for="{{list}}" wx:key="index" >
            <image src="{{item.fileID}}"></image>
        </view>
    </view>
    <view wx:for="{{videolist}}" wx:key="index">
        <video src="{{item.videofileID}}"></video>
    </view>
<button bindtap="choose" type="primary">上传</button>

wxss

image{
    width: 360rpx;
    height: 350rpx;
}
video{
    width: 100%;
    height: 500rpx;
}
.first{
    display: flex;
}

文件的上传及下载

wx.chooseMessageFile官方文档:wx.chooseMessageFile | 微信开放文档 (qq.com)

wx.cloud.downloadFile官方文档:​​​​​​wx.cloud.downloadFile | 微信开放文档 (qq.com)

在微信开发者工具中编译上传文件会在本地端选择文件,在真机中则是从客户端选择文件进行上传,调用wx.cloud.downloadFile下载文件后,文件会自动打开。word,excel,ptf等都可以上传。

js:

Page({
    chooseFlie(){
        wx.chooseMessageFile({
            count: 1,
            type: 'all',
            success (res) {
                console.log(res)
              // tempFilePath可以作为 img 标签的 src 属性显示图片
              const tempFilePaths = res.tempFiles
              console.log(res.tempFiles[0].path)
              console.log(res.tempFiles[0].name)
              wx.cloud.uploadFile({
                  cloudPath:res.tempFiles[0].name,
                  filePath:res.tempFiles[0].path
              }).then(res=>{
                  console.log('上传成功',res)
              }).catch(err=>{
                  console.log('上传失败',err)
              })
            }
          })
    },
    // 获取用户输入的下载链接
    getContent(e){
        console.log(e.detail.value)
        this.setData({
            fileId:e.detail.value
        })
    },
    // 下载文件
    downloadFile(){
        let fileId = this.data.fileId
        console.log('下载链接',fileId)
       if(fileId != null && fileId.length > 0){
            wx.cloud.downloadFile({
                fileID:fileId
            }).then(res=>{
                console.log('下载成功',res)
                wx.openDocument({
                filePath: res.tempFilePath,
                success: function (res) {
                    console.log('打开文档成功',res)
                }
                })
            }).catch(err=>{
                console.log('下载失败',err)
                wx.showToast({
                  icon:'error',
                  title: '输入的链接有误',
                })
            })
       }else{
           wx.showToast({
               icon:'none',
               title: '下载链接为空',
           })
       }
    }
})

ml:

<button bindtap="chooseFlie" type="primary">选择文件</button>
请输入下载链接
<input bindinput="getContent"></input>
<button bindtap="downloadFile" type="primary">点击下载</button>

css:

input{
    border: 1px solid black;
}

执行效果:

 

 控制台打印出的文件链接即为下载文件的地址

点击下载后,文档下载完成会自动打开

 

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到