const PERMISSION = ["android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"];
const FOLDER_NAME = "自定义地址"
export default {
created() {
// #ifdef APP-PLUS
//获取当前设备的默认环境路径
const Environment = plus.android.importClass("android.os.Environment");
this.filePathTemp = "file://" + Environment.getExternalStorageDirectory() + this.FOLDER_NAME + "/";
// 接口请求地址
this.address = this.downloadUrl;
// #endif
},
methods: {
/**
* H5端下载d
*/
downloadFileH5() {
uni.showLoading({
title: "下载中...",
});
const link = document.createElement("a");
link.href = this.downloadUrl;
link.download = "测试文件"; // 设置下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
/**
* APP端下载
*/
// 请求存储权限
requestStoragePermission() {
return new Promise((resolve, reject) => {
plus.android.requestPermissions(
PERMISSION,
(result) => {
console.log("权限申请结果", result);
if (result.granted?.length === PERMISSION.length && result.deniedPresent?.length === 0) {
resolve();
} else {
reject("权限申请失败!");
}
},
(error) => {
reject(error);
console.error("权限申请失败", error);
}
);
});
},
// 下载文件并保存到自定义文件夹
downloadFileApp() {
// 请求存储权限
this.requestStoragePermission()
.then(() => {
uni.downloadFile({
url: this.address,// 文件的下载地址
success: (res) => {
console.log(res, res.statusCode);
if (res.statusCode === 200) {
this.downloadFileSave(res.tempFilePath);
} else {
uni.showToast({
title: "下载失败,请重试",
icon: "none",
});
}
},
fail: (err) => {
console.error("下载失败:", err);
uni.showToast({
title: "下载请求失败,请检查网络连接",
icon: "none",
});
},
});
})
.catch(() => {
console.error("没有存储权限,无法保存文件");
uni.showToast({
title: "没有存储权限",
icon: "none",
});
});
},
// 保存文件
downloadFileSave(tempFilePath) {
const filenameFortemp = tempFilePath.split("/").pop(); // 获取文件名
const tempFileNamePath = this.filePathTemp + this.callerPhone.trim() + "." + filenameFortemp.split(".").pop();
console.log(filenameFortemp, tempFileNamePath, tempFilePath, 1111);
const dtask = plus.downloader.createDownload(
this.address,
{
filename: tempFileNamePath,
timeout: 10, // 设置超时
retry: 3, // 重试次数
retryInterval: 5, // 重试间隔
},
(download, status) => {
if (status === 200) {
console.log("文件下载成功,保存路径:" + download.filename);
uni.showToast({
title: "文件已保存在 " + this.FOLDER_NAME,
icon: "none",
});
} else {
console.log("下载失败,状态码:" + status);
uni.showToast({
title: "下载失败",
icon: "none",
});
}
}
);
dtask.start(); // 开始下载任务
},
},
};
在uniapp中下载文件到APP的指定目录和H5的下载
最新推荐文章于 2025-05-28 16:37:43 发布