vue 读取本地TXT GBK编码文件

vue  读取本地TXT GBK编码文件,利用ajax 访问本地static  data 文件。

安装 iconv-lite 插件   iconv-lite

 npm i iconv-lite -S

代码:

readFile() {
    const url = '/static/data/spectators_index_20200802.txt'
const _this = this
const json = []
let xhr = null if (window.XMLHttpRequest) { // code for all new browsers xhr = new XMLHttpRequest() } else if (window.ActiveXObject) { // code for IE5 and IE6 xhr = new ActiveXObject('Microsoft.XMLHttp') } if (xhr != null) { xhr.open('get', url, true)
xhr.responseType = 'arraybuffer' //设置数据类型
xhr.onload = () = >{ if (xhr.status === 200) { const iconv = require('iconv-lite') // 引入node iconv-lite插件 把GBK编码转utf8编码 const data = new Uint8Array(xhr.response)
const text = iconv.decode(data, 'gbk') //解析成字符串 // console.log(text); if (text) { const arr = text.split('\n') if (arr != null && arr.length > 0) { let obj = {} for (let i = 0; i
< arr.length; i++) { if (i > 0) { const val = arr[i].split(' ') if (val[0] === '01') { obj.a1 = val[val.length - 1] } } } } } } } xhr.send() } else { alert('你的浏览器不支持XMLHttpRequest功能') } },

 

posted on 2020-10-15 08:58  奔跑吧人生  阅读(4337)  评论(0编辑  收藏  举报

导航