抖音开放平台Logo
控制台

FileSystemManager.readFile
收藏
我的收藏

基础库 1.15.0 开始支持本方法,这是一个异步方法。

读取本地文件内容。

前提条件
业务背景
使用限制
注意事项
readFile 可以用于 用户目录(ttfile://user) 临时目录(ttfile://temp) 以及 包内目录(访问包内目录不需要加额外协议头)
相关教程

语法

FileSystemManager.readFile(options)

参数说明

options 为 object 类型,属性如下:

属性名类型默认值必填说明最低支持版本
encodingenum
指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容
1.15.0
filePathstring
要读取的文件的路径
1.15.0
successfunction
接口调用成功的回调函数
1.15.0
failfunction
接口调用失败的回调函数
1.15.0
completefunction
接口调用结束的回调函数(调用成功、失败都会执行)
1.15.0

encoding 的合法值

说明最低支持版本
utf-8
-
1.15.0
ascii
-
1.15.0
base64
-
1.15.0
binary
-
1.15.0
hex
-
1.15.0
ucs2
以小端序读取
1.15.0
ucs-2
以小端序读取
1.15.0
utf16le
以小端序读取
1.15.0
utf-16le
以小端序读取
1.15.0
utf8
-
1.15.0
latin1
-
1.15.0

回调成功

object 类型,属性如下:

属性名类型说明最低支持版本
datastring
数据。string 或 ArrayBuffer 类型
1.15.0
errMsgstring
"FileSystemManager.readFile:ok"
1.15.0

回调失败

object 类型,属性如下:

属性名类型说明最低支持版本
errMsgstring
"FileSystemManager.readFile:fail" + 详细错误信息
1.15.0

错误码

errNoerrMsg说明最低支持版本
20000readFile:fail filePath is invalid
filePath 参数错误
1.99.0
20001readFile:fail param should be xxx, but got xxx
参数校验错误
1.99.0
21101readFile:fail permission denied, readFile {filePath_value}
无操作权限(filePath 路径不可读)
1.99.0
21102readFile:fail operation not permitted, readFile {filePath_value}
类型不正确(不是文件路径)
1.99.0
21103readFile:fail no such file or directory, readFile {filePath_value}
filePath 文件不存在
1.99.0

代码示例

const fileSystemManager = tt.getFileSystemManager();

tt.chooseImage({
  success(res) {
    readFile(res.tempFilePaths[0]);
  },
});

function readFile(filePath) {
  fileSystemManager.readFile({
    filePath,
    success(res) {
      // 输出读取的文件内容
      console.log(res.data);
    },
    fail(res) {
      console.log("调用失败", res.errMsg);
    },
  });
}