天天看点

微信小程序云开发-云存储-上传文件(word/excel/ppt/pdf)到云存储

说明 word/excel/ppt/pdf是从客户端会话选择文件。使用chooseMessageFile中选择文件。

一、wxml文件

上传按钮,绑定chooseFile

<!--上传文件(word/excel/ppt/pdf等)到云存储-->
<button bindtap="chooseFile" type="primary" >上传文件</button>      

二、wxss文件

wxss设置按钮外边距

button{
  margin: 30rpx;
}      

三、js文件

实现文件选择和文件上传的功能

Page({
  //功能:上传文件(word/excel/ppt/pdf等)到云存储

  //第一步:选择文件
  chooseFile(){
    let that = this
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles
        let tempFile = tempFilePaths[0]
        that.uploadFile(tempFile.name,tempFile.path)
      }
    })
  },
  //第二步:通过uploadFile上传选中的文件
  uploadFile(fileName,tempFile){
    wx.cloud.uploadFile({
      cloudPath:fileName,
      filePath:tempFile,
    })
  .then(res=>{
    console.log("上传成功啦",res);
    wx.showToast({
      title: '文件上传成功',
      icon:"success",
      duration:2000
    })
  })
  .catch(err=>{
    console.log("上传失败啦",err);
  })
  }
  
})      

四、效果展示

微信小程序云开发-云存储-上传文件(word/excel/ppt/pdf)到云存储