uniapp下載&打開實現方案,支持安卓ios和h5
Android:
1、申請本地存儲讀寫權限
2、創建文件夾(文件夾不存在即創建)
3、下載文件
ios:
1、下載文件
2、保存到本地,需要打開文件點擊儲存
使用方法:
downloadFile(fileUrl, fileName)
file.js
let downloadFilePath = '/storage/emulated/0/yulong-ys-files'
// 創建文件夾
export const createDir = () => {return new Promise((resolve, reject) => {// 申請本地存儲讀寫權限plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE','android.permission.READ_EXTERNAL_STORAGE','android.permission.INTERNET','android.permission.ACCESS_WIFI_STATE'], success => {const File = plus.android.importClass('java.io.File')let file = new File(downloadFilePath)// 文件夾不存在即創建if (!file.exists()) {file.mkdirs()resolve()}resolve()}, error => {Tips.toast('無法獲取權限,文件下載將出錯')reject(error)})})}// 下載文件操作
async function doDownloadFile(url, fileName, options, osName) {if (osName === 'Android') {await createDir()}Tips.loading('正在下載...')let dTask = plus.downloader.createDownload(url, options, async (d, status) => {Tips.hideLoading()if (status == 200) {plus.io.convertLocalFileSystemURL(d.filename)await Tips.confirm('文件已保存,是否打開?')uni.openDocument({filePath: d.filename,success: () => {console.log('成功打開')}})} else {console.log('下載失敗')console.log(d)Tips.toast('下載失敗')Tips.hideLoading()plus.downloader.clear()}})dTask.start()
}// 下載文件
export function downloadFile(url, fileName) {if (!url) {Tips.toast('下載地址不能為空')return Promise.reject('下載地址不能為空')}// #ifdef H5window.location.href = url// #endif// #ifdef APP-PLUSlet osName = plus.os.name;if (osName === 'Android') {doDownloadFile(url, fileName, {filename: 'file://' + downloadFilePath + '/' + fileName}, osName)} else {doDownloadFile(url, fileName, {}, osName)}// #endif
}
Tips.js
/*** 提示與加載工具類*/
export default class Tips {constructor() {this.isLoading = false;}/*** 彈出提示框*/static success(title, duration = 1000) {setTimeout(() => {uni.showToast({title: title,icon: "success",mask: true,duration: duration});}, 300);if (duration > 0) {return new Promise((resolve, reject) => {setTimeout(() => {resolve();}, duration);});}}/*** 彈出確認窗口*/static confirm(content, ops = {}, payload = {}) {return new Promise((resolve, reject) => {uni.$showModal({content: content,...ops,success: res => {if (res.confirm) {resolve(payload);} else if (res.cancel) {reject(payload);}},fail: res => {reject(payload);}});});}static toast(title, onHide = undefined, icon = "none") {setTimeout(() => {uni.showToast({title: title,icon: icon,mask: true,duration:1500});}, 0);// 隱藏結束回調if (onHide) {setTimeout(() => {onHide();}, 1500);}}/*** 錯誤框*/static error(title, onHide) {uni.showToast({title: title,icon: 'error',mask: true,duration: 1500});// 隱藏結束回調if (onHide) {setTimeout(() => {onHide();}, 1500);}}/*** 彈出加載提示*/static loading(title = "加載中") {if (Tips.isLoading) {return;}Tips.isLoading = true;uni.showLoading({title: title,mask: true});}/*** 加載完畢*/static hideLoading() {if (Tips.isLoading) {Tips.isLoading = false;uni.hideLoading();}}
}/*** 靜態變量,是否加載中*/
Tips.isLoading = false;
參考博客,在次基礎上做了修改