【原生小程序-下载文件、预览文件、上传文件】

// 下载
  dowload:function () {
    let t = this
    wx.downloadFile({
      url: this.data.enclosure_resume.enclosure,
      success (res) {
          wx.saveFile({
              tempFilePath: res.tempFilePath,
              success (res) {
                $.msg(0,'下载成功')
                setTimeout(() => {
                  // 预览文件
                  wx.openDocument({ 
                    filePath: wx.env.USER_DATA_PATH + "/" + t.data.enclosure_resume.title,//这样写可以修改文件的名字
                    showMenu: true,//可以通过预览文件下载文件
                    fileType: 'pdf',
                    success: function (res) {
                      console.log(res,'打开文档成功');
                    }
                  })
                }, 2000)
              },
              fail(error){
                $.msg(0,'网络繁忙,请稍后重试~')
              }
          })
      }
  })
},
// 上传
uploadFile:function () {
  let that = this
  wx.chooseMessageFile({
    count: 1,     //能选择文件的数量
    type: 'file',   //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
    success(res) { 
      var size = res.tempFiles[0].size;
      var filename = res.tempFiles[0].name;
      var newfilename = filename + "";  
      console.log(res,1111)
  if (size > 5000000||newfilename.indexOf(".pdf")==0){ //我还限制了文件的大小和具体文件类型
        wx.showToast({
          title: '文件大小不能超过5MB,格式必须为pdf!',
          icon: "none",
          duration: 2000,
          mask: true
        })
      }else{
        $.upload({url:'member/upload/index',file:res.tempFiles[0].path},function(r){
          wx.showToast({
            title: '上传成功',
            icon: "none",
            duration: 2000
          })
          let params = {
            name:filename,
            file_id:r.data.file_id
          }
        })
      }
    }
  })
},

封装的$.upload

upload:function(o,f){
    var t=this,d={
      url:'',
      file:'',
      name:'file',
      data:{}
    };
    for(var i in d){
      if(o[i]) d[i]=o[i]
    }
    d.data['platform']='miniprogram',
    d.data['user-token']=t.visitor.token,
    wx.uploadFile({
      url:t.siteDomain+'/'+t.siteVersion+'/'+d.url,//上传接口
      filePath:d.file,
      name:d.name,
      formData:d.data,
      header:{
        'Content-Type':'multipart/form-data',
        'accept':'application/json'
      },
      success(r){
        r.data=JSON.parse(r.data),
        t.callback(r,f)
      },
      fail(r){
        this.msg(0,'上传失败')
      }
    })
  },
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值