uniapp:下载文件,并保存到手机文件夹

2023-05-22  本文已影响0人  小李不小
uni.downloadFile({
    url: url,//文件的下载路径
    success(res) {
        //保存到本地
        uni.saveFile({
            tempFilePath: res.tempFilePath,//文件的临时路径
            success: function(res) {
                const savedFilePath = res.savedFilePath;
                // 打开文件
                uni.openDocument({
                    filePath: savedFilePath,
                    success: function(res) {
                        uni.hideLoading()
                    },
                    fail: function(res) {},
                    complete: function(res) {
                        setTimeout(uni.hideLoading(), 4000)
                    },
                });
            },
            fail: function(err) {   }
        });
    },
    fail(res) {}
})
##注意:虽然能保存到本地,但是保存的位置非常奇怪
例如:(安卓端)"内部存储\Android\data\io.dcloud.HBuilder\apps\HBuilder\doc\uniapp_save"
位置不方便用户查找,并且文件名在保存到本地的过程中,还被篡改了
所以建议采用方法二

方法二
uni.showLoading({
title: '正在下载'
});
// 本地路径开头使用file://,跟上手机文件本地目录storage/emulated/0,
// 这时用户文件管理器能看到的了,之后创建 连信 作为文件夹,
// 后缀是用于文件命名和格式修改,大家可以使用变量。
var url = this.downFileSrc;
let dtask = plus.downloader.createDownload(url, {
    filename: "file://storage/emulated/0/连信/" + this.downFileName //利用保存路径,实现下载文件的重命名
},(d, status)=> {
    //d为下载的文件对象
    if (status == 200) {
        uni.hideLoading();
        uni.showToast({
            icon: 'none',
            mask: true,
            title: '已保存到文件夹:/连信/' + this.downFileName, //保存路径
            duration: 3000,
        });
        //下载成功,d.filename是文件在保存在本地的相对路径,使用下面的API可转为平台绝对路径
        let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
        setTimeout(()=>{
            plus.runtime.openFile(d.filename); //选择软件打开文件
        },1500)
    } else {
        //下载失败
        uni.hideLoading();
        plus.downloader.clear(); //清除下载任务
        uni.showToast({
            icon:'none',
            mask:true,
            title: '下载失败,请稍后重试',
        });
    }
})
dtask.start();

上一篇下一篇

猜你喜欢

热点阅读