tt.getFileInfo
收藏
我的收藏

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

获取文件信息。

前提条件
业务背景
使用限制
注意事项
支持沙盒
相关教程

语法

tt.getFileInfo(options)

参数说明

options 为 object 类型,属性如下:

属性名类型默认值必填说明最低支持版本
digestAlgorithmenummd5
计算文件摘要的算法
1.81.0
filePathstring
要读取的文件路径
1.15.0
successfunction
接口调用成功的回调函数
1.15.0
failfunction
接口调用失败的回调函数
1.15.0
completefunction
接口调用结束的回调函数(调用成功、失败都会执行)
1.15.0

digestAlgorithm 的合法值

说明最低支持版本
sha1
sha1 算法
1.81.0
md5
md5 算法
1.81.0

回调成功

object 类型,属性如下:

属性名类型说明最低支持版本
sizenumber
文件大小,以字节为单位
1.15.0
digeststring
按照传入的 digestAlgorithm 计算得出的的文件摘要
1.15.0
errMsgstring
"getFileInfo:ok"
1.15.0

回调失败

object 类型,属性如下:

属性名类型说明最低支持版本
errMsgstring
"getFileInfo:fail " + 错误信息
1.15.0

错误码

errNoerrMsg说明最低支持版本
20000getFileInfo:fail filePath is invalid
filePath 参数错误
1.99.0
21101getFileInfo:fail permission denied, getFileInfo %s
文件路径不可读
1.99.0
21102getFileInfo:fail no such file or directory, getFileInfo %s
文件不存在
1.99.0
21103getFileInfo:fail operation not permitted, getFileInfo %s
filePath 类型不是文件
1.99.0

扫码体验

请使用字节宿主APP扫码

代码示例

开发者工具中预览

<!-- index.ttml -->
<view class="container">
  <button type="primary" bindtap="saveFile">保存文件到本地</button>
  <button type="primary" bindtap="getFile">获取文件信息</button>
</view>
// index.js
const url =
  "https://sf1-cdn-tos.douyinstatic.com/obj/microapp/frontend/download.png"
Page({
  data: {
    filePath: "",
  },

  saveFile() {
    tt.downloadFile({
      url,
      success: (res) => {
        console.log("临时文件下载成功,下载路径: " + res.tempFilePath)
        tt.saveFile({
          tempFilePath: res.tempFilePath,
          success: (data) => {
            tt.showModal({
              content: "临时文件保存成功",
              showCancel: false,
            })
            this.setData({
              filePath: data.savedFilePath,
            })
            console.log("文件保存在本地路径: " + data.savedFilePath)
          },
          fail: (res) => {
            tt.showModal({
              content: "临时文件保存失败",
              showCancel: false,
            })
          },
        })
      },
      fail: (res) => {
        console.log("下载失败: ", res.errMsg)
      },
    })
  },

  getFile() {
    if (!this.data.filePath) {
      return tt.showToast({
        title: "请先保存文件",
        icon: "none",
      })
    }
    tt.getFileInfo({
      filePath: this.data.filePath,
      digestAlgorithm: "md5",
      success: (data) => {
        // 成功回调返回的参数中,size属性为文件大小,以字节为单位
        tt.showModal({
          title: "文件信息:",
          content: "大小:" + data.size + "字节,md5:" + data.digest,
          showCancel: false,
        })
      },
      fail: (res) => {
        // 当 API 执行失败后调用, 预定义返回消息格式为${API_NAME}:fail
        console.log("API调用失败: " + res.errMsg, res)
        tt.showModal({
          content: "获取文件信息失败",
          showCancel: false,
        })
      },
      complete(res) {
        // 当 API 执行完成(无论成功或者失败)后都会调用, 预定义返回消息格式为${API_NAME}:ok / fail
        console.log("API调用完成: " + res.errMsg)
      },
    })
  },
})