Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat small program API upload, download


May 18, 2021 WeChat Mini Program Development Document


Table of contents


wx.uploadFile(OBJECT)


Upload local resources to the developer server. T his interface allows a page to upload a local resource to a specified server after it has acquired a temporary file path to a local resource through an interface such as wx.chooseImage. The client initiates an HTTPS POST request, where Content-Type is multipart/form-data

OBJECT parameter description:

Parameters Type Required Description
Url String Is Developer server url
filePath String Is The path to upload the file resource
name String Is The key for the file, through which the developer can obtain the file binary content on the server side
header Object Whether HTTP Request Header, Referer cannot be set in Header
formData Object Whether Additional form data in http requests
success Function Whether The interface calls a successful callback function
fail Function Whether The interface calls the failed callback function
complete Function Whether Callback function at end of interface call (call succeeds, fails are executed)

Success returns a description of the parameters:

Parameters Type Description
data String The data returned by the developer server
statusCode Number HTTP status code

Example code:

wx.chooseImage({
  success:function(res){
    var tempFilePaths = res.tempFilePaths
    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      }
    })
  }
})

Return value:

Base library 1.4.0 starts to support, and low versions need to be compatible.

Returns an uploadTask that listens uploadTask progress events and cancels upload tasks.

uploadTask

Basic Library 1.4.0 began support, low version needs to do Compatibility

A object that can listen to upload progress changes, and cancel the object of uploading

method:

UploadTask.abort()

Base library 1.4.0 starts to support, and low versions need to be compatible.

Interrupt the upload task


UploadTask.offHeadersReceived(function callback)

Base library 2.1.0 starts to support, and low versions need to be compatible.

Cancel listening to the HTTP Response Header event

Parameters

function callback

The callback function for the HTTP Response Header event


UploadTask.offProgressUpdate(function callback)

Base library 2.1.0 starts to support, and low versions need to be compatible.

Cancel listening for upload progress change events

Parameters

function callback

Upload a callback function for progress change events


UploadTask.onHeadersReceived(function callback)

Base library 2.1.0 starts to support, and low versions need to be compatible.

Listen for http Response Header events. the event will be completed earlier than requested

Parameters

function callback

The callback function for the HTTP Response Header event

Parameters

Object res
Property Type Description
header Object HTTP Response Header returned by the developer server


UploadTask.onProgressUpdate(function callback)

Base library 1.4.0 starts to support, and low versions need to be compatible.

Listen for upload progress change events

Parameters

function callback

Upload a callback function for progress change events

Parameters

Object res
Property Type Description
progress number Upload the percentage of progress
totalBytesSent number The length of the data that has been uploaded, in bytes
totalBytesExpectedToSend number The total length of data expected to be uploaded, in bytes


Example code:

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() // 取消上传任务

Bug & Tip

  1. tip The maximum number of synth limits is 10
  2. tip : The default timeout and the maximum timeout are 60s


wx.downloadFile(OBJECT)

Download the file resources locally. The client initiates an HTTP GET request directly, returning the file's local temporary path.

Parameters

Object object

Property Type The default Required Description The lowest version
Url string Is Download the url of the resource
header Object Whether Referer cannot be set in header for HTTP requests
timeout number Whether Time-out in milliseconds 2.10.0
filePath string Whether Specify the path stored after the file is downloaded (local path) 1.8.0
success function Whether The interface calls a successful callback function
fail function Whether The interface calls the failed callback function
complete function Whether Callback function at end of interface call (call succeeds, fails are executed)

object.success callback function

Parameters
Object res
Property Type Description The lowest version
tempFilePath string Temporary file path (local path). When filePath is not passed in to specify the file storage path, it returns and the downloaded file is stored in a temporary file
filePath string The user file path (local path). Returns when filePath is passed in, consistent with the incoming filePath
statusCode number The HTTP status code returned by the developer server
profile Object Some debug information during the network request process 2.10.4

The structure of res.profile

Property Type Description
redirectStart number The time at which the first HTTP redirect occurred. Redirects that have a jump and are within the same domain name are counted, otherwise the value is 0
redirectEnd number The time at which the last HTTP redirect was completed. A redirect that has a jump and is inside the same domain name is counted, otherwise the value is 0
fetchStart number The time the component is ready to crawl resources using HTTP requests, which occurs before the local cache is checked
domainLookupStart number The time at which DNS domain name queries start, if a local cache (i.e. no DNS queries) or persistent connections are used, are equal to the fetchStart value
domainLookupEnd number The time at which DNS domain name queries are completed is equal to the fetchStart value if a local cache (i.e., no DNS queries) or persistent connections are used
connectStart number Http (TCP) starts to establish a connection at the same time as fetchStart values if it is a persistent connection. Note If an error occurs at the transport layer and the connection is re-established, the time at which the newly established connection starts is shown here
connectEnd number Http (TCP) completes the time it takes to establish the connection (completes the handshake), or is equal to the fetchStart value if the connection is persistent. N ote If an error occurs in the transport layer and the connection is re-established, the time when the newly established connection is completed is shown here. Note that the handshake here ends, including secure connection establishment completed and SOCKS authorization passed
SSLconnectionStart number The time the SSL established the connection, or 0 if it is not a secure connection
SSLconnectionEnd number The time the SSL was established to complete, or 0 if it is not a secure connection
requestStart number HTTP requests to read the time at which the real document started (the connection was established), including reading the cache locally. When the connection is incorrectly reconnected, it is also shown here when the new connection was established
requestEnd number The time at which the HTTP request reads the end of the real document
responseStart number The time it took for HTTP to start receiving responses (getting to the first byte), including reading the cache locally
responseEnd number The HTTP response all receives the completed time (getting to the last byte), including reading the cache locally
Rtt number Rtt in real time during the connection of the request
estimate_nettype string Assessed network status slow 2g/2g/3g/4g
httpRttEstimate number The protocol layer evaluates the rtt of the current network based on multiple requests (for informational purposes only)
transportRttEstimate number Rtt for the current network evaluated by the transport layer based on multiple requests (for informational purposes only)
downstreamThroughputKbpsEstimate number Evaluate the kbps currently downloaded on the network
throughputKbps number The actual download of kbps for the current network
peerIP string The IP currently requested
port number The port currently requested
socketReused boolean Whether to re-use the connection
sendBytesCount number The number of bytes sent
receivedBytedCount number The number of bytes received

Returns a value

DownloadTask

Base library 1.4.0 starts to support, and low versions need to be compatible.

An object that can listen for download progress change events and cancel downloads


Example code:

wx.downloadFile({
  url: 'https://example.com/audio/123', //仅为示例,并非真实的资源
  success (res) {
    // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
    if (res.statusCode === 200) {
      wx.playVoice({
        filePath: res.tempFilePath
      })
    }
  }
})



DownloadTask

Base library 1.4.0 starts to support, and low versions need to be compatible.

An object that can listen for changes in download progress and cancel download tasks

Method:

DownloadTask.abort()

Base library 1.4.0 starts to support, and low versions need to be compatible.

Interrupt the download task


DownloadTask.offHeadersReceived(function callback)

Base library 2.1.0 starts to support, and low versions need to be compatible.

Cancel listening to the HTTP Response Header event

Parameters

function callback

The callback function for the HTTP Response Header event


DownloadTask.offProgressUpdate(function callback)

Base library 2.1.0 starts to support, and low versions need to be compatible.

Cancel listening for download progress events

Parameters

function callback

Download the callback function for the progress change event

DownloadTask.onHeadersReceived(function callback)

Base library 2.1.0 starts to support, and low versions need to be compatible.

Listen for http Response Header events. the event will be completed earlier than requested

Parameters

function callback

The callback function for the HTTP Response Header event

Parameters

Object res
Property Type Description
header Object HTTP Response Header returned by the developer server

DownloadTask.onProgressUpdate(function callback)

Base library 1.4.0 starts to support, and low versions need to be compatible.

Listen for download progress change events

Parameters

function callback

Download the callback function for the progress change event

Parameters

Object res
Property Type Description
progress number Percentage of download progress
totalBytesWritten number The length of the data that has been downloaded, in Bytes
totalBytesExpectedToWrite number The total length of data expected to be downloaded, in Bytes