uni-app 文件下载
// 文件下载
通用永久下载(下载到默认位置,暂不支持下载到指定位置)
var fileHttpUrl = '文件地址';
uni.showLoading({
mask: true,
title: '下载中'
});
uni.downloadFile({
url: fileHttpUrl,
success: function(res) {
// console.log(res.tempFilePath);
var filePath = res.tempFilePath;
uni.saveFile({
tempFilePath: filePath,
success: function(r) {
uni.hideLoading();
var savedFilePath = r.savedFilePath;
uni.showToast({
title: '文件已下载到' + savedFilePath,
icon: 'none',
duration: 5000
});
},
fail: function(res) {
console.log(res);
uni.hideLoading();
uni.showToast({
title: '下载失败',
icon: 'none'
});
}
});
},
fail: function(res) {
console.log(res);
uni.hideLoading();
uni.showToast({
title: '下载失败',
icon: 'none'
});
}
});
app下载到指定位置
uni.showLoading({
mask: true,
title: '下载中'
});
var task = plus.downloader.createDownload(fileHttpUrl, {}, function (d, status) {
// 下载完成
if (status == 200) {
uni.hideLoading();
let fileUrl = plus.io.convertLocalFileSystemURL(d.filename);
// 根据路径获取文件对象
uni.hideLoading();
plus.io.resolveLocalFileSystemURL(
fileUrl,
fileEntry => {
// 获取存储空间根目录
plus.io.resolveLocalFileSystemURL(
'/storage/emulated/0/',
entryc => {
// 在根目录创建一个名为'downloads'的目录(没有就创建,有就打开)
entryc.getDirectory(
'downloads',
{ create: true },
success => {
// 最后将文件复制到创建的目录下(移动可使用moveTo,但是moveTo有时会失败)
fileEntry.copyTo(
success,
'',
function (entry) {
console.log(entry.fullPath);
uni.hideLoading();
var savedFilePath = entry.fullPath;
uni.showToast({
title: '文件已下载到' + savedFilePath,
icon: 'none',
duration: 5000
});
},
function (e) {
console.log('----', e);
uni.hideLoading();
uni.showToast({
title: '下载失败' + e.errMsg,
icon: 'none'
});
}
);
},
fail => {
console.error('+++', fail);
uni.hideLoading();
uni.showToast({
title: '下载失败' + fail.errMsg,
icon: 'none'
});
}
);
},
fail => {
console.error('===', fail);
uni.hideLoading();
uni.showToast({
title: '下载失败' + fail.errMsg,
icon: 'none'
});
}
);
},
fail => {
console.error(fail);
uni.hideLoading();
uni.showToast({
title: '下载失败',
icon: 'none'
});
}
);
} else {
console.log(status);
uni.hideLoading();
uni.showToast({
title: '下载失败',
icon: 'none'
});
}
});
task.start();