描述
我们在使用uniapp官方提供的uni.downloadFile以及uni.saveFile时,会发现,这个文件下载的位置和我们预想的不太一样,这个文件会下载到android/data/你的项目包及以下内容,乍看下来似乎没有什么,但是就实机环境而言,如果我们下载的是音频内容,那么本地的音乐软件是无法扫描到android/data目录下的内容的【涉及到安全】,但是我们又不可能把软件包移出去,那么我们就需要把文件下载到外面的文件夹中
解决方案
我们需要先在storage/emulated/0/目录下创建一个文件夹【这个目录应该是适用于绝大多数安卓机】,我们需要向用户申请本地文件读写的权限,根据测试,如果只是在manifest.json中配置有关权限似乎是无用的,那么我们就需要手动向用户申请,并创建文件夹,这需要使用以下代码
const createDir = async(path) => {
//申请本地存储读写权限
plus.android.requestPermissions([
'android.permission.WRITE_EXTERNAL_STORAGE',
'android.permission.READ_EXTERNAL_STORAGE',
'android.permission.INTERNET',
'android.permission.ACCESS_WIFI_STATE'
], error => {
const File = plus.android.importClass('java.io.File');
let file = new File(path);
if (!file.exists()) { //文件夹不存在即创建
return file.mkdirs();
}
return false;
}, success=> {
uni.showToast({
title: '无法获取权限,文件下载将出错!',
icon: 'none',
})
})
}
path值为:” /storage/emulated/0/自定义文件夹名称”
创建完文件夹后,我们就需要将文件下载到这里了,这时我们需要使用plus.downloader.createDownload以及plus.io.convertLocalFileSystemURL方法,这里我提供官网地址:https://www.html5plus.org/doc/zh_cn/downloader.html
而代码可以使用如下形式:
export const downMusic = async (url : string, song : string, singer : string) => {
try {
const last = getLast(url); // 文件格式后缀【使用时根据状况进行修改】
const fileName = singer.replace(/\//g, "&") + '-' + song + '.' + last;
const downPath=useIndexStore().downPath; //你的自定义下载路径
//注意:url是你要下载的文件路径
let dtask = plus.downloader.createDownload(url, {
//1.本地路径开头使用file://;
//示例格式为:file:///storage/emulated/0/abc/test.txt 根据具体情况进行修改
filename: "file://"+downPath+"/" + fileName //利用保存路径,实现下载文件的重命名
}, (down, status) => {//down为下载的文件对象;status下载状态
console.log(down)
if (status == 200) {//下载成功
console.log("下载成功")
//down.filename是把文件在保存在本地的相对路径上,我们还需要使用下面的plus.io.convertLocalFileSystemURL转为绝对路径
let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
uni.showToast({
title: song,
icon: 'success',
duration: 2000
})
} else {//下载失败
console.log("下载失败")
plus.downloader.clear(); //清除下载任务
}
}
);
dtask.start();//启用
} catch (error) {
console.log('下载出现错误');
}
}
以上代码仅供参考,请根据实际状况进行修改。整体流程即
指定文件夹目录->创建目录->使用plus.downloader.createDownload下载内容->指定fileName为下载路径即文件名->使用plus.io.convertLocalFileSystemURL转换路径【可能不用也可以】