uni-app 下載文件(四)

uni.downloadFile(OBJECT)
下載文件資源到本地,客戶端直接發起一個 HTTP GET 請求,返回文件的本地臨時路徑。服務器

OBJECT 參數說明函數

參數名 類型 必填 說明
url String 是 下載資源的 url
header Object 否 HTTP 請求 Header, header 中不能設置 Referer
success Function 否 下載成功後以 tempFilePath 的形式傳給頁面,res = {tempFilePath: '文件的臨時路徑'}
fail Function 否 接口調用失敗的回調函數
complete Function 否 接口調用結束的回調函數(調用成功、失敗都會執行)
注:文件的臨時路徑,在應用本次啓動期間能夠正常使用,如需持久保存,需在主動調用 uni.saveFile,才能在應用下次啓動時訪問獲得。測試

success 返回參數說明url

參數 類型 說明
tempFilePath String 臨時文件路徑,下載後的文件會存儲到一個臨時文件
statusCode Number 開發者服務器返回的 HTTP 狀態碼
示例code

uni.downloadFile({對象

url: 'https://www.example.com/file/test', //僅爲示例,並不是真實的資源
success: function (res) {
    if (res.statusCode === 200) {
        console.log('下載成功');
    }
}

});
返回值接口

返回一個 downloadTask 對象,經過 downloadTask,可監聽上傳進度變化事件,以及取消上傳任務。事件

downloadTask 對象的方法列表資源

方法 參數 說明 最低版本
onProgressUpdate callback 監聽下載進度變化 *
abort   中斷下載任務 *
onProgressUpdate 返回參數說明開發

參數 類型 說明
progress Number 下載進度百分比
totalBytesWritten Number 已經下載的數據長度,單位 Bytes
totalBytesExpectedToWrite Number 預期須要下載的數據總長度,單位 Bytes
示例

const downloadTask = uni.downloadFile({

url: 'http://www.example.com/file/test', //僅爲示例,並不是真實的資源
success: function (res) {
    if (res.statusCode === 200) {
        console.log('下載成功');
    }
}

});

downloadTask.onProgressUpdate(function (res) {

console.log('下載進度' + res.progress);
console.log('已經下載的數據長度' + res.totalBytesWritten);
console.log('預期須要下載的數據總長度' + res.totalBytesExpectedToWrite);

// 測試條件,取消下載任務。
if (res.progress > 50) {
    downloadTask.abort();
}

});

相關文章
相關標籤/搜索