WeChat applet: text reading and writing and network request

1. Local user file read and write:

1. Common interface operation file:

(1) Write the content of the file:

const fm = wx.getFileSystemManager()   // 获取文件管理器
fm.writeFileSync(`${wx.env.USER_DATA_PATH}/文件名.txt`,  '文件内容', 'utf8')  //在本地用户目录创建文件(不存在时),并写入内容

(2) Read the contents of the file:

const fm = wx.getFileSystemManager() // 获取文件管理器
//1>同步方式读取:
try {
  const fileContent = fm.readFileSync(`${wx.env.USER_DATA_PATH}/文件名.txt`, 'utf8', 0)
  console.log("onLoad >> 读文件成功,文件内容: " + fileContent)
} catch(exception) {
  console.log('onLoad >> 读文件失败, 异常消息: ', exception)
}
//2>异步方式读取:
fm.readFile({filePath: `${wx.env.USER_DATA_PATH}/文件名.txt`, encoding: 'utf8',
  success(response) {
    console.log("onLoad >> 读文件成功,文件内容: " + response.data)
  },
  fail(exception) {
    console.log('onLoad >> 读文件失败, 异常消息: ', exception)
  }
})

2. FD interface operation file (applicable to a large number of file operations):

(1) Write the content of the file:

const fm = wx.getFileSystemManager() // 获取文件管理器
var fd = fm.openSync({filePath: `${wx.env.USER_DATA_PATH}/文件名.txt`, flag: "w+"}) // 打开文件,a+为读取和追加写入方式打开、w+为读取和截断写入方式打开
var content = 'FD接口方式-文件内容'
fm.writeSync({data: content, fd: fd, encoding: 'utf8', length: content.length, position: 0}) // 写入文件内容
fm.closeSync({fd: fd}) // 关闭文件

(2) Read the contents of the file:

const fm = wx.getFileSystemManager() // 获取文件管理器
var arrayBuffer = new ArrayBuffer(1024);
//1>同步方式读取:
try {
  var fd = fm.openSync({filePath: `${wx.env.USER_DATA_PATH}/文件名.txt`, flag: "a+"}) // 打开文件,a+为读取和追加写入方式打开、w+为读取和截断写入方式打开
  fm.readSync({fd: fd,
    arrayBuffer: arrayBuffer,  //数据写入的缓冲区
    length: 1024               //读取的字节数,默认0
  }) // 读取文件内容
  var enc = new TextDecoder("utf-8");
  var fileContent = enc.decode(arrayBuffer) //将ArrayBuffer转为字符串
  console.log("onShow >> 读文件成功,文件内容: " + fileContent)
  fm.closeSync({fd: fd}) // 关闭文件
} catch(exception) {
  console.log('onShow >> 读文件失败, 异常消息: ', exception)
}
//2>异步方式读取:
fm.open({
  filePath: `${wx.env.USER_DATA_PATH}/文件名.txt`,
  flag: 'a+',
  success(response) {
    fm.read({
      fd: response.fd,
      arrayBuffer: arrayBuffer,
      length: 1024,
      success(response) {
        var enc = new TextDecoder("utf-8");
        var fileContent = enc.decode(arrayBuffer) //将ArrayBuffer转为字符串
        console.log("onShow >> 读文件成功,文件内容: " + fileContent)
      }
    })
  },
  fail(exception) {
    console.log('onShow >> 读文件失败, 异常消息: ', exception)
  }
})

2. Network request:

Configure server domain name:

Enter the following address, click the Modify button in the server domain name -> add "request legal domain name, uploadFile legal domain name, downloadFile legal domain name":

Applets

1. Interface request (POST/GET):

var doRequest = function (url, { isPost=true }) {
  console.log("开始接口请求 >>")
  wx.request({
    url: url, //请求URL
    data: { //请求参数
      key1: 'value1'
    },
    header: { //头字段
      'content-type': 'application/json'
    },
    method: isPost ? 'POST' : 'GET', //请求方法
    timeout: 15000, //超时时间
    enableHttp2: true, //开启HTTP2
    success(response) { //请求成功
      console.log("接口请求 response HTTP状态码: " + response.statusCode + "  数据: " + response.data)
      if (response.statusCode != 200) return
      //...解析返回的json数据
    },
    fail(response) { //请求失败
      console.log("接口请求 response 错误码: " + response.errno + "  错误信息: " + response.errMsg)
    }
  })
}

2. Upload files:

var doUploadFile = function (url, uploadFilePath) {
  console.log("开始上传文件 >>")
  wx.request({
    url: url, //请求URL
    filePath: uploadFilePath,  //待上传文件路径
    name: 'file', //与后端约定的上传文件key
    formData: { //请求参数
      key1: 'value1'
    },
    header: { //头字段
      'key1': 'value1'
    },
    timeout: 60000, //超时时间
    success(response) { //上传成功
      console.log("上传文件成功 HTTP状态码: " + response.statusCode + "  数据: " + response.data)
      if (response.statusCode != 200) return
      //...解析返回的json数据
    },
    fail(response) { //上传失败
      console.log("上传文件失败 错误信息: " + response.errMsg)
    }
  })
}

3. Download the file:

var doDownloadFile = function (url, saveFilePath) {
  console.log("开始下载文件 >>")
  wx.downloadFile({
    url: url, //请求URL
    filePath: saveFilePath,  //文件本地保存路径,例:wx.env.USER_DATA_PATH + "/a.jpeg"
    header: { //头字段
      'key1': 'value1'
    },
    timeout: 60000, //超时时间
    success(response) { //下载成功,文件路径为:http://usr/a.jpeg
      console.log("下载文件成功 HTTP状态码: " + response.statusCode + "  文件路径: " + saveFilePath)
      if (response.statusCode != 200) return
      //...处理下载完后的逻辑
    },
    fail(response) { //下载失败
      console.log("下载文件失败 错误信息: " + response.errMsg)
    }
  })
}

4. Connect WebSocket:

var webSocket  = function (wsUrl) {
  console.log("开始连接WebSocket >>")
  wx.connectSocket({
    url: wsUrl,  //WebSocket地址
    header:{ //头字段
      'content-type': 'application/json'
    },
    protocols: ['protocol1'],  //子协议数组
    timeout: 60000,  //超时时间
    success(response) { //连接成功
      console.log("连接WebSocket成功 data: " + response.data)
    },
    fail(response) { //连接失败
      console.log("连接WebSocket失败 错误码: " + response.errno + "  错误信息: " + response.errMsg)
    }
  })
}

Guess you like

Origin blog.csdn.net/a526001650a/article/details/128146156