showFile
文件读写功能,支持读取和写入文件,支持小程序、H5、App端。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.getFileSystemManager | UniApp['getFileSystemManager'] | 获取文件系统管理器(小程序/App端) |
deps.fetch | Window['fetch'] | 获取 fetch 函数(H5端必需) |
deps.Blob | Window['Blob'] | 创建 Blob(H5端必需) |
deps.createObjectURL | Window['URL']['createObjectURL'] | 创建对象 URL(H5端必需) |
deps.revokeObjectURL | Window['URL']['revokeObjectURL'] | 撤销对象 URL(H5端必需) |
deps.createElement | Document['createElement'] | 创建元素(H5端必需) |
deps.body | Document['body'] | 获取 body(H5端必需) |
deps.FileReader | new () => FileReader | 创建 FileReader(H5端必需) |
deps.detectEnvironment | () => 'h5' | 'miniapp' | 'app' | 'unknown' | 检测环境函数(可选) |
deps.log | Console['log'] | 日志输出 |
deps.error | Console['error'] | 错误输出 |
环境要求
- UniApp环境: 使用UniApp API,支持小程序、H5、App端
- H5端: 需要提供完整的浏览器API依赖
函数签名
typescript
function readFile(
options: FileOptions,
deps: ShowFileDeps
): Promise<FileResult>
function writeFile(
options: FileOptions,
deps: ShowFileDeps
): Promise<FileResult>
interface ShowFileDeps {
getFileSystemManager: UniApp['getFileSystemManager']
fetch?: Window['fetch']
Blob?: Window['Blob']
createObjectURL?: Window['URL']['createObjectURL']
revokeObjectURL?: Window['URL']['revokeObjectURL']
createElement?: Document['createElement']
body?: Document['body']
FileReader?: new () => FileReader
detectEnvironment?: () => 'h5' | 'miniapp' | 'app' | 'unknown'
log: Console['log']
error: Console['error']
}
interface FileOptions {
filePath?: string
data?: string | ArrayBuffer
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'ucs-2' | 'utf16le' | 'utf-16le' | 'utf8' | 'utf-8'
extraData?: Record<string, unknown>
}
interface FileResult {
errMsg?: string
data?: string | ArrayBuffer
filePath?: string
savedFilePath?: string
raw?: unknown
}参数
readFile
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
options | FileOptions | 是 | 文件选项 |
options.filePath | string | 是 | 文件路径 |
options.encoding | string | 否 | 文件编码 |
deps | ShowFileDeps | 是 | 依赖注入对象 |
writeFile
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
options | FileOptions | 是 | 文件选项 |
options.filePath | string | 是 | 文件路径 |
options.data | string | ArrayBuffer | 是 | 要写入的数据 |
options.encoding | string | 否 | 文件编码 |
deps | ShowFileDeps | 是 | 依赖注入对象 |
返回值
| 函数 | 类型 | 说明 |
|---|---|---|
readFile | Promise<FileResult> | Promise,成功时返回文件内容 |
writeFile | Promise<FileResult> | Promise,成功时返回写入结果 |
工作原理
- 环境检测:根据
detectEnvironment函数检测当前运行环境 - 平台适配:
- 小程序端:使用
uni.getFileSystemManager - H5端:使用
fetch、Blob、FileReader等浏览器API - App端:使用
uni.getFileSystemManager
- 小程序端:使用
- 文件操作:根据环境调用对应的文件操作接口
- 返回结果:返回文件操作结果
支持多平台统一接口,自动适配不同环境的实现差异。