8.1.2 上传下载

在小程序开发过程中,经常会用到文件上传下载功能。这就会用到网络交互上传下载API。

1.上传

wx.uploadFile(OBJECT)

上传API,将本地资源上传到开发者服务器。如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data 。 OBJECT参数说明,如表8-3所示:

表8-3

参数名 类型 必填 说明
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返回参数说明,如表8-4所示:

表8-4

参数名 类型 说明
data String 开发者服务器返回的数据
statusCode Number HTTP状态码

示例代码:

wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'https://xxxx.xxxx.com/upload', // 上传路径url,仅为示例,非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

注意:

  • 最大并发限制是 10 个。
  • 默认超时时间和最大超时时间都是 60s。

2.下载

wx.downloadFile(OBJECT)

下载API,下载文件资源到本地。客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。 OBJECT参数说明如表8-5所示:

表8-5

参数名 类型 必填 说明
url String 下载资源的 url
header Object HTTP 请求 Header
success Function 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'}
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

wx.downloadFile({
  url: 'http://xxxx.xxxx.com/download/123', //下载资源url,仅为示例,并非真实的资源
  success: function(res) {
    wx.playVoice({
      filePath: res.tempFilePath
    })
  }
})

注意:

  • 最大并发限制是 10 个。
  • 默认超时时间和最大超时时间都是 60s。
  • 文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wx.saveFile,在小程序下次启动时才能访问得到。
  • 网络请求的 referer 是不可以设置的,格式固定为 https://servicewechat.com/{appid}/{version}/ page-frame.html ,其中 {appid} 为小程序的 appid,{version} 为小程序的版本号,版本号为 0 表示为开版。
  • 6.5.3 以及之前版本的 iOS 微信客户端 header 设置无效。

results matching ""

    No results matching ""