兼容ios和android
function downloadFileIOS(downFileSrc) {
uni.showLoading({
title: '正在下载'
})
const downloadTask = uni.downloadFile({
url: downFileSrc,
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功');
}
uni.saveFile({
tempFilePath: res.tempFilePath,
success: function(red) {
uni.hideLoading()
uni.showModal({
title: '提示',
content: '如需保存到本地,需要打开文件点击储存',
// cancelText: '我知道了',
confirmText: '打开文件',
success: function(res) {
if (res.confirm) {
uni.openDocument({
filePath: red.savedFilePath,
success: (sus) => {
console.log('成功打开');
}
})
}
}
})
}
})
}
})
}
function downloadFile(downFileSrc, file_name, ext) {
// #ifdef APP-PLUS
uni.showLoading({
title: '正在下载'
})
let that = propsThis
const downloadTask = plus.downloader.createDownload(downFileSrc, { //文件的下载地址 {
// filename: 'file://storage/emulated/0/Download/' + file_name , //服务器 app 的下载地址
filename: '', //利用保存路径,实现下载文件的重命名
},
function(downloadResult, status) {
uni.hideLoading();
if (status === 200) {
console.log('下载文件中....', that.fileStatus)
that.fileStatus = true
that.fileNameDownload = file_name
//downloadResult.filename是文件在保存在本地的相对路径,使用下面的API可转为平台绝对路径
let fileSaveUrl = plus.io.convertLocalFileSystemURL(downloadResult.filename);
plus.runtime.openFile(d.filename); //选择软件打开文件
} else { //下载失败
console.log("下载失败")
plus.downloader.clear(); //清除下载任务
}
}
);
downloadTask.start(); //执行下载
//#endif
}
// propsThis = this
function DownLoadFile(file, propsThis) {
if (uni.getSystemInfoSync().platform === "ios") {
downloadFileIOS(file.file_url)
propsThis.$u.post(propsThis.apis.createFileLog, {
file_id: file.file_id,
type: 2
})
} else {
// const fileType = propsThis.getFileType(file.ext)
// if (fileType === null) {
// uni.showToast({
// title: '暂不支持该文件的下载!',
// icon: 'error',
// duration: 2000,
// position: 'center'
// });
// return
// }
var _propsThis = propsThis
plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'], function(e) {
if (e.deniedAlways.length > 0) { //权限被永久拒绝
// 弹出提示框解释为何需要读写手机储存权限,引导用户打开设置页面开启
uni.showModal({
title: '存储权限',
content: '您拒绝了存储权限,请去设置-应用开启存储权限。',
success: function(res) {
if (res.confirm) {
// console.log('用户点击确定');
} else if (res.cancel) {
// console.log('用户点击取消');
}
}
});
}
if (e.deniedPresent.length > 0) { //权限被临时拒绝
// 弹出提示框解释为何需要读写手机储存权限,可再次调用plus.android.requestPermissions申请权限
plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'])
// console.log('666666666 ' + e.deniedPresent.toString());
}
if (e.granted.length > 0) { //权限被允许
downloadFile(file.file_url, file.file_name, file.ext)
_propsThis.$u.post(_propsThis.apis.createFileLog, {
file_id: file.file_id,
type: 2
})
}
}, function(e) {});
}
}
使用
DownLoadFile(this.detail, this)