8.3 文件

使用API对小程序中出现的各类文件进行操作。

wx.saveFile(OBJECT)

保存文件到本地。

OBJECT参数说明(表8-23): 表8-23

参数 类型 必填 说明
tempFilePath String 需要保存的文件的临时路径
success Function 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'}
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

wx.saveFile({
  success: function(res) {
    var tempFilePath = res.tempFilePath    //获取文件保存的路径
    wx.saveFile({
      tempFilePath: tempFilePath,
      success: function(res) {
        var savedFilePath = res.savedFilePath
      }
    })
  }
})

本地文件存储的大小限制为10M

wx.getSavedFileList(OBJECT)

获取本地已保存的文件列表。

OBJECT参数说明(表8-24): 表8-24

参数 类型 必填 说明
success Function 接口调用成功的回调函数,返回结果见success返回参数说明
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

success返回参数说明(表8-25): 表8-25

参数 类型 说明
errMsg String 接口调用结果
fileList Object Array 文件列表

fileList中的项目说明(表8-26): 表8-26

类型 说明
filePath String 文件的本地路径
createTime Number 文件的保存时的时间戳,从1970/01/01 08:00:00 到当前时间的秒数
size Number 文件大小,单位B

示例代码:

wx.getSavedFileList({
  success: function(res) {
    console.log(res.fileList)             //打印全部列表
    console.log(res.fileList[0].filePath)           //打印第一项的文件路径
  }
})

wx.getSavedFileInfo(OBJECT)

获取本地文件的文件信息

OBJECT参数说明(表8-27): 表8-27

参数 类型 必填 说明
filePath String 文件路径
success Function 接口调用成功的回调函数,返回结果见success返回参数说明
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

success返回参数说明(表8-28): 表8-28

参数 类型 说明
errMsg String 接口调用结果
size Number 文件大小,单位B
createTime Number 文件的保存是的时间戳,从1970/01/01 08:00:00 到当前时间的秒数

示例代码:

wx.getSavedFileInfo({
  filePath: 'wxfile://somefile', //仅做示例用,非真正的文件路径
  success: function(res) {
    console.log(res.size)
    console.log(res.createTime)
  }
})

wx.removeSavedFile(OBJECT)

删除本地存储的文件

OBJECT参数说明(表8-29): 表8-29

参数 类型 必填 说明
filePath String 需要删除的文件路径
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

wx.getSavedFileList({
  success: function(res) {
    if (res.fileList.length > 0){
      wx.removeSavedFile({
        filePath: res.fileList[0].filePath,       //此路径为文件列表第一项的路径
        complete: function(res) {
          console.log(res)
        }
      })
    }
  }
})

wx.openDocument(OBJECT)

新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx

OBJECT参数说明(表8-30): 表8-30

参数 类型 必填 说明
filePath String 文件路径,可通过 downFile 获得
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

wx.downloadFile({
  url: 'http://example.com/somefile.pdf',    //演示地址
  success: function (res) {
    var filePath = res.tempFilePath       //获取下载文件地址
    wx.openDocument({
      filePath: filePath,
      success: function (res) {
        console.log('打开文档成功')
      }
    })
  }
})

results matching ""

    No results matching ""