下載
downloadFile
TIP
該API使用方法為: DownloadTask wx.downloadFile(Object object)
TIP
請在服務端響應的header中指定合理的Content-Type欄位,以保證用戶端正確處理文件類型。
功能說明: 下載文件資源到本地。 用戶端直接發起一個HTTPS GET請求,返回文件的本地臨時路徑(本地路徑),單次下載允許的最大文件為200MB。 使用前請參攷閱 相關說明。
參數及說明: Object object。
内容 類型 必填 說明 url string 是 下載資源的url header Object 否 HTTP請求的Header,Header中不能設定Referer filePath string 否 指定文件下載後存儲的路徑 success Function 否 接口調用成功的回呼函數 fail Function 否 接口調用失敗的回呼函數 complete Function 否 接口調用結束的回呼函數(無論成功與否都執行) object.success回呼函數參數: Object res。
内容 類型 說明 tempFilePath string 暫存文件路徑(本地路徑)。 沒傳入filePath指定檔存儲路徑時會返回,下載後的文件會存儲到一個暫存文件 filePath string 用戶文件路徑(本地路徑)。 傳入filePath時會返回,跟傳入的filePath一致 statusCode number 開發者服務器返回的HTTP狀態碼 返回值: DownloadTask
示例代碼:
wx.downloadFile({
url: 'https://example.com/audio/123', // This is merely an example, not an actual resource.
success (res) {
// As long as the server has response data, the response content will be written into the file and enter the success callback. It is up to the business side to determine whether the desired content has been downloaded.
if (res.statusCode === 200) {
wx.playVoice({
filePath: res.tempFilePath
})
}
}
})DownloadTask
.abort
TIP
該API使用方法為: DownloadTask.abort()
- 功能說明: 中斷下載任務。
.onProgressUpdate
TIP
該API使用方法為: DownloadTask.onProgressUpdate(function listener)
功能說明: 監聽下載進度變化事件。
參數及說明: function listener,下載進度變化事件的監聽函數。
内容 類型 說明 progress number 下載進度百分比 totalBytesWritten number 已經下載的數據長度,單位Bytes totalBytesExpectedToWrite number 預期需要下載的數據總長度,單位Bytes
.offProgressUpdate
TIP
該API使用方法為: DownloadTask.offProgressUpdate(function listener)
功能說明: 移除下載進度變化事件的監聽函數
參數及說明: function listener,onProgressUpdate傳入的監聽函數。 不傳此參數則移除所有監聽函數。
示例代碼:
const listener = function (res) { console.log(res) }
DownloadTask.onHeadersReceived(listener)
DownloadTask.offHeadersReceived(listener) // Pass the same function object used for listening..onHeadersReceived
TIP
該API使用方法為: DownloadTask.onHeadersReceived(function listener)
功能說明: 監聽HTTP Response Header事件。 會比請求完成事件更早。
參數及說明: function listener,HTTP Response Header事件的監聽函數。
内容 類型 說明 header Object 開發者服務器返回的HTTP Response Header
.offHeadersReceived
TIP
該API使用方法為: DownloadTask.offHeadersReceived(function listener)
功能說明: 移除HTTP Response Header事件的監聽函數。
參數及說明: function listener,onHeadersReceived傳入的監聽函數。 不傳此參數則移除所有監聽函數。
示例代碼:
const listener = function (res) { console.log(res) }
DownloadTask.onHeadersReceived(listener)
DownloadTask.offHeadersReceived(listener) // Pass the same function object used for listening.- 示例代碼:
const downloadTask = wx.downloadFile({
url: 'http://example.com/audio/123', // This is merely an example, not an actual resource.
success (res) {
wx.playVoice({
filePath: res.tempFilePath
})
}
})
downloadTask.onProgressUpdate((res) => {
console.log('Download progress', res.progress)
console.log('Length of data already downloaded', res.totalBytesWritten)
console.log(''Length of data expected to be downloaded', res.totalBytesExpectedToWrite)
})
downloadTask.abort() // Aborts the download task