小程序文档特别差,写的不清晰,很容易误解,坑无数人,举个栗子。

微信小程序文件读写报错:

FileSystemManager.readFile()  读文件报错---   FileSystemManager is not defined

wx.readFile()      读文件报错---       wx.readFile is not a function

正确打开方式:wx.getFileSystemManager().readFile

代码如下:

wx.getFileSystemManager().readFile({filePath:'http://tmp/wxc0251b33f337548a.o6zAJs6HdKKYcZRWkZSKvjMthh6M.axIum1rsCntv0d3c724f67df142083bbc60073a61cae.txt',       encoding:'utf-8',       success: res = {          //返回临时文件路径          console.log(res.data)               },       fail: console.error      })     return;    wx.cloud.downloadFile({      fileID: 'cloud://mingziyun-341ef5.6d69-mingziyun-341ef5/2000.txt', // 文件 ID      success: res = {        // 返回临时文件路径        console.log(res.tempFilePath)         wx.getFileSystemManager().writeFile({         })      },      fail: console.error    })

 

本地缓存文件

本地存储文件只能通过调用特定接口产生,不能直接写入内容。本地缓存文件产生后,重启之后仍可用。本地缓存文件只能通过 saveFile 接口将本地临时文件保存获得。

示例

wx.saveFile({tempFilePath: '', // 传入一个本地临时文件路径success(res) {  console.log(res.savedFilePath) // res.savedFilePath 为一个本地缓存文件路径}})

本地缓存文件是最初的设计,1.7.0 版本开始,提供了功能更完整的本地用户文件,可以完全覆盖本地缓存文件的功能,如果不需要兼容低于1.7.0 版本,可以不使用本地缓存文件。 

本地用户文件

本地用户文件是从 1.7.0 版本开始新增的概念。我们提供了一个用户文件目录给开发者,开发者对这个目录有完全自由的读写权限。通过wx.env.USER_DATA_PATH 可以获取到这个目录的路径。

示例

 

// 在本地用户文件目录下创建一个文件 a.txt,写入内容 "hello, world"const fs = wx.getFileSystemManager()fs.writeFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'hello, world', 'utf8')

 

 

 

TAG标签: 微信小程序writefile

http://www.xiaochengxub.com/read-103654.html