隔了好几天,昨天导师说要验收啦!捉急!!!加紧进度得做出来了小程序~
1.微信小程序使用wx.downloadFile(OBJECT)进行文件下载(临时保存),返回文件的临时存储路径。该次存储只有本次小程序启动时有效,如需永久保存需调用wx.saveFile进行保存。先看下wx.downloadFile的参数列表↓
| 参数 | 类型 | 必填 | 必填 |
|---|---|---|---|
| url | String | 是 | 下载资源的 url |
| header | Object | 否 | HTTP 请求 Header,header 中不能设置 Referer |
| success | Function | 否 | 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} |
| fail | Function | 否 | 接口调用失败的回调函数 |
| complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
2.可以使用downloadFil的返回值downloadTask监测下载进度,downloadTask的对象方法列表↓
| 方法 | 参数 | 说明 | 最低版本 |
|---|---|---|---|
| onProgressUpdate | callback | 监听下载进度变化 | 1.4.0 |
| abort | 中断下载任务 | 1.4.0 |
)| 参数 | 类型 | 说明 |
|---|---|---|
| progress | Number | 下载进度百分比 |
| totalBytesWritten | Number | 已经下载的数据长度,单位 Bytes |
| totalBytesExpectedToWrite | Number | 预期需要下载的数据总长度,单位 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() // 取消下载任务 }}).usual_progres{ width: 100%; height: 20px; }(4)效果图(只观察下载部分)
(5)查看控制台的log输出,“保存成功啦”上面是downloadFile的success回调,下半部分是saveFile的success输出。













