微信小程序API之网络(三)下载数据

来源:互联网 发布:js 获取table tr td 编辑:程序博客网 时间:2024/05/21 01:56

隔了好几天,昨天导师说要验收啦!捉急!!!加紧进度得做出来了小程序~


1.微信小程序使用wx.downloadFile(OBJECT)进行文件下载(临时保存),返回文件的临时存储路径。该次存储只有本次小程序启动时有效,如需永久保存需调用wx.saveFile进行保存。先看下wx.downloadFile的参数列表↓


参数类型必填必填urlString是下载资源的 urlheaderObject否HTTP 请求 Header,header 中不能设置 ReferersuccessFunction否下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'}failFunction否接口调用失败的回调函数completeFunction否接口调用结束的回调函数(调用成功、失败都会执行)

2.可以使用downloadFil的返回值downloadTask监测下载进度,downloadTask的对象方法列表↓


方法参数说明最低版本onProgressUpdatecallback监听下载进度变化1.4.0abort 中断下载任务1.4.0(1)onProgressUpdate返回值说明。(然而我做测试的时候,只有progress一个返回值,另外两个都没有哭


参数类型说明progressNumber下载进度百分比totalBytesWrittenNumber已经下载的数据长度,单位 BytestotalBytesExpectedToWriteNumber预期需要下载的数据总长度,单位 Bytes


3.还是用tomcat,造一个资源地址。(上一篇博客中记录了,此处不再赘述)

(1)附上wxml代码,button绑定方法“downloadFromServer”在js中定义

<view class="container wxml-container">  <text class="topic-group">下载</text>  <button class="button" bindtap="downloadFromServer">下载数据</button>  <progress class='usual_progres' show-info percent='{{downloadPercent}}'></progress>  </view>

(2)js文件

// pages/api/api.jsPage({  data: {    downloadPercent:0  },  downloadFromServer: function () {    const downloadTask = wx.downloadFile({      url: 'http://xxx.xxx.xxx.xxx:8080/wxapp/GIF1.gif', //开启tomcat后的本机ip地址      success: function (res) {        console.log(res)        wx.saveFile({//对临时资源进行永久保存          tempFilePath: res.tempFilePath,//tempFilePath想要保存的文件的临时地址          success:function(res){            console.log("保存成功啦")            console.log(res)//res是保存成功的返回值,包含存储路径等          }        })      }    })    downloadTask.onProgressUpdate((res) => {      console.log('下载进度', res.progress)      this.setData({        downloadPercent: (res.progress*100).toFixed(2)//toFixed(2)取小数点后两位,更新wxml中progress组件的进度值      })    })    //downloadTask.abort() // 取消下载任务  }})


(3)progress样式

.usual_progres{  width: 100%;    height: 20px;  }

(4)效果图(只观察下载部分)




(5)查看控制台的log输出,“保存成功啦”上面是downloadFile的success回调,下半部分是saveFile的success输出。


阅读全文
0 0
原创粉丝点击