一、獲取文件路徑
在進行下載文件之前,我們需要先獲取到要下載的文件的URL或者URI。
對於URL或者URI的獲取,可以通過以下方式:
// 使用uni.request 發起GET請求
uni.request({
url: 'http://httpbin.org/get',
success: function (res) {
console.log(res.data);
}
});
如果我們要獲取遠程服務器上的圖片,則可以像下面這樣獲取:
uni.request({
url:"http://www.test.com/if_1.jpg",
success(res) {
let filePath = res.tempFilePath
}
})
二、下載文件
接下來,我們需要用uni.downloadFile從服務器上下載文件,下載成功後就可以將其保存在本地存儲中。
uni.downloadFile({
url: "要下載的文件鏈接",
success(res){
console.log(res.tempFilePath)
uni.saveFile({
tempFilePath: res.tempFilePath,
success(res) {
console.log('下載成功,文件保存在:' + res.savedFilePath)
},
fail(res){
console.log('下載失敗')
}
})
}
})
三、顯示下載進度
為了更好地讓用戶了解下載的進度,可以實現一個進度條,實時顯示下載進度。
代碼示例:
uni.downloadFile({
url: "要下載的文件鏈接",
success(res){
console.log(res.tempFilePath)
uni.saveFile({
tempFilePath: res.tempFilePath,
success(res) {
console.log('下載成功,文件保存在:' + res.savedFilePath)
},
fail(res){
console.log('下載失敗')
}
})
},
onProgressUpdate(res){
console.log('下載進度' + res.progress + '%')
}
})
四、下載失敗的處理
當下載失敗時,我們需要為用戶提供友好的錯誤信息,提示用戶文件下載失敗。
示例代碼如下:
uni.downloadFile({
url:"要下載的文件鏈接",
success(res){
// 下載成功
},
fail(res) {
uni.showToast({
title: '文件下載失敗',
icon: 'none'
})
}
})
以上就是實現uniapp文件下載到手機的全過程。在實際應用場景中,可能還需要結合業務需求進行優化和擴展。
原創文章,作者:OMGAE,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/368650.html