uniapp下载&打开实现方案,支持安卓ios和h5,下载文件到指定目录,安卓文件管理内可查看到

uniapp下载&打开实现方案,支持安卓ios和h5

Android:

1、申请本地存储读写权限

2、创建文件夹(文件夹不存在即创建)

3、下载文件

ios:

1、下载文件

2、保存到本地,需要打开文件点击储存

使用方法:

js 复制代码
downloadFile(fileUrl, fileName)

file.js

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 H5
  window.location.href = url
  // #endif
  // #ifdef APP-PLUS
  let osName = plus.os.name;
  if (osName === 'Android') {
    doDownloadFile(url, fileName, {filename: 'file://' + downloadFilePath + '/' + fileName}, osName)
  } else {
    doDownloadFile(url, fileName, {}, osName)
  }
  // #endif
}

Tips.js

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;

参考博客,在次基础上做了修改

相关推荐
iOS阿玮29 分钟前
永远不要站在用户的对立面,挑战大众的公知。
uni-app·app·apple
xw52 小时前
uni-app中v-if使用”异常”
前端·uni-app
!win !2 小时前
uni-app中v-if使用”异常”
前端·uni-app
黄林晴3 小时前
如何判断手机是否是纯血鸿蒙系统
android
火柴就是我3 小时前
flutter 之真手势冲突处理
android·flutter
法的空间4 小时前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios
循环不息优化不止4 小时前
深入解析安卓 Handle 机制
android
恋猫de小郭4 小时前
Android 将强制应用使用主题图标,你怎么看?
android·前端·flutter
jctech4 小时前
这才是2025年的插件化!ComboLite 2.0:为Compose开发者带来极致“爽”感
android·开源
用户2018792831674 小时前
为何Handler的postDelayed不适合精准定时任务?
android