微信小程序中如何上传和下载文件

Posted on 2021-06-29 15:33  求知若渴;虚心若愚  阅读(2541)  评论(0编辑  收藏  举报

.wxml

<button bindtap="chooseFile">选择文件</button>

<view>请输入下载链接</view>
<input bindinput="getContent"></input>
<button bindtap="downLoad">下载</button>

.js

Page({
  chooseFile(){   //上传文件
    var that=this
    wx.chooseMessageFile({
    count: 1,
    type: 'all',
    success (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFiles
    console.log(tempFilePaths[0])
    that.upload(tempFilePaths[0].path,tempFilePaths[0].name)
    }
    })
    },
    
     upload(tmpFile,updFile){ //修改
      wx.cloud.uploadFile({
      cloudPath: updFile, //修改
      filePath: tmpFile, // 文件路径
      success: res => {
      // get resource ID
      console.log("上传成功",res)
      },
      fail: err => {
      // handle error
      console.log("上传失败",err)
      }
      })
      },

     
  //下载并打开文件


      getContent(e){
        console.log(e.detail.value)
        this.setData({
        fileID:e.detail.value
        })
        },
        downLoad(){
        var fileID
        fileID=this.data.fileID
        console.log("下载链接为:",fileID)
        wx.cloud.downloadFile({
        fileID: fileID,
        success: res => {
          // get temp file path
          console.log("下载成功",res)
          const filePath = res.tempFilePath  //新增
          wx.openDocument({ //新增加
            filePath: filePath, //新增加
            success: function (res) { //新增加
            console.log('打开文档成功') //新增加
            }
            })
            
          },
          fail: err => {
          // handle error
          console.log("下载失败",res)
          }
          })
          },













    })

 

Copyright © 2024 求知若渴;虚心若愚
Powered by .NET 8.0 on Kubernetes