一,wx.request
发起网络请求
参数名 | 类型 | 必填 | 默认值 | 说明 |
---|---|---|---|---|
url | String | 是 | 开发者服务器接口地址 | |
data | Object/String/ArrayBuffer | 否 | 请求的参数 | |
header | Object | 否 | 设置请求的 header,header 中不能设置 Referer。 | |
method | String | 否 | GET | 有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT |
dataType | String | 否 | json | 如果设为json,会尝试对返回的数据做一次 JSON.parse |
responseType | String | 否 | text | 设置响应的数据类型。合法值:text、arraybuffer |
success | Function | 否 | 收到开发者服务成功返回的回调函数 | |
fail | Function | 否 | 接口调用失败的回调函数 | |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
success返回参数说明:
参数名 | 类型 | 说明 |
---|---|---|
data | Object/String/ArrayBuffer | 开发者服务器返回的数据 |
statusCode | Number | 开发者服务器返回的 HTTP 状态码 |
header | Object | 开发者服务器返回的 HTTP Response Header |
示例代码:
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
console.log(res.data)
}
})
二,文件上传
wx.uploadFile:将本地资源上传到开发者服务器,客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
url | String | 是 | 开发者服务器 url |
filePath | String | 是 | 要上传文件资源的路径 |
name | String | 是 | 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 |
header | Object | 否 | HTTP 请求 Header, header 中不能设置 Referer |
formData | Object | 否 | HTTP 请求中其他额外的 form data |
success | Function | 否 | 接口调用成功的回调函数 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
success返回参数说明:
参数名 | 类型 | 说明 |
---|---|---|
data | String | 开发者服务器返回的数据 |
statusCode | Number | 开发者服务器返回的 HTTP 状态码 |
示例代码:
const uploadTask = wx.uploadFile({
url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success: function(res){
var data = res.data
//do something
}
})
uploadTask.onProgressUpdate((res) => {
console.log('上传进度', res.progress)
console.log('已经上传的数据长度', res.totalBytesSent)
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
})
uploadTask.abort() // 取消上传任务
onProgressUpdate 返回参数说明:
参数名 | 类型 | 说明 |
---|---|---|
progress | Number | 上传进度百分比 |
totalBytesSent | Number | 已经上传的数据长度,单位 Bytes |
totalBytesExpectedToSend | Number | 预期需要上传的数据总长度,单位 Bytes |
三,文件下载
下载文件资源到本地
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
url | String | 是 | 下载资源的 url |
header | Object | 否 | HTTP 请求 Header,header 中不能设置 Referer |
success | Function | 否 | 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: ‘文件的临时路径’} |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wx.saveFile,才能在小程序下次启动时访问得到。
const downloadTask = wx.downloadFile({
url: 'http://example.com/audio/123', //仅为示例,并非真实的资源
success: function(res) {
wx.playVoice({
filePath: res.tempFilePath
})
}
})
downloadTask.onProgressUpdate((res) => {
console.log('下载进度', res.progress)
console.log('已经下载的数据长度', res.totalBytesWritten)
console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
})
downloadTask.abort() // 取消下载任务